shell sort


See On Github

Data

Contributor

Generic placeholder thumbnail

by jcla1

in go

Source Code

package shellSort

func ShellSort(arr []int) []int {
	h := len(arr) / 2
	var val, i int

	for h > 0 {
		for j := h; j < len(arr); j++ {
			val = arr[j]
			i = j

			for i >= h && arr[i-h] > val {
				arr[i] = arr[i-h]
				i -= h
			}

			arr[i] = val
		}

		h /= 2
	}
	return arr
}
package shellSort

import "testing"

func TestShellSort(t *testing.T) {
	arrs := [][]int{[]int{-2, 1, -3, 4, -1, 2, 1, -5, 4}, []int{2, 3, 7, -5, -1, 4, -10}}

	var result []int

	for _, arr := range arrs {
		result = ShellSort(arr)
		if !isSorted(result) {
			t.Errorf("ShellSort(%v) = %v", arr, result)
		}
	}
}

func isSorted(arr []int) bool {
	for i := 1; i < len(arr); i++ {
		if arr[i-1] > arr[i] {
			return false
		}
	}

	return true
}