mirror of
https://github.com/0xAX/go-algorithms
synced 2024-11-13 13:10:30 +00:00
46b32e8b0e
* odd-even sort added * heap sort added
60 lines
1.1 KiB
Go
60 lines
1.1 KiB
Go
package main
|
|
|
|
/*
|
|
* Heap sort - https://en.wikipedia.org/wiki/Heapsort
|
|
*/
|
|
|
|
import "fmt"
|
|
|
|
import "github.com/0xAX/go-algorithms"
|
|
|
|
func sift(arr []int, i int, arrLen int) []int {
|
|
done := false
|
|
|
|
tmp := 0
|
|
maxChild := 0
|
|
|
|
for (i * 2 + 1 < arrLen) && (!done) {
|
|
if i * 2 + 1 == arrLen - 1 {
|
|
maxChild = i * 2 + 1
|
|
} else if (arr[i * 2 + 1] > arr[i * 2 + 2]) {
|
|
maxChild = i * 2 + 1
|
|
} else {
|
|
maxChild = i * 2 + 2
|
|
}
|
|
|
|
if arr[i] < arr[maxChild] {
|
|
tmp = arr[i]
|
|
arr[i] = arr[maxChild]
|
|
arr[maxChild] = tmp
|
|
i = maxChild
|
|
} else {
|
|
done = true
|
|
}
|
|
}
|
|
|
|
return arr
|
|
}
|
|
|
|
func main() {
|
|
arr := utils.RandArray(10)
|
|
fmt.Println("Initial array is:", arr)
|
|
fmt.Println("")
|
|
|
|
i := 0
|
|
tmp := 0
|
|
|
|
for i = len(arr) / 2 - 1; i >= 0; i-- {
|
|
arr = sift(arr, i, len(arr))
|
|
}
|
|
|
|
for i = len(arr) - 1; i >= 1; i-- {
|
|
tmp = arr[0];
|
|
arr[0] = arr[i];
|
|
arr[i] = tmp;
|
|
arr = sift(arr, 0, i);
|
|
}
|
|
|
|
fmt.Println("Sorted array is: ", arr)
|
|
}
|