Created
December 15, 2022 23:13
-
-
Save abdulrahmanAlotaibi/dd6540391f1b19397d4326f53055247f to your computer and use it in GitHub Desktop.
Insertion Sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
func main(){ | |
fmt.Printf("Inerstion sort: %d", insertionSort([]int{2,3,-1,-4,9,1,2,0})) | |
} | |
// Take j and compare it with all the prevous elements | |
// We assume that the prevous eleemnts is the biggest elements in the list (ascdening) | |
func insertionSort(arr[]int)[]int{ | |
for i:= 1 ; i < len(arr) ; i++{ | |
j:=i | |
for j > 0 && arr[j] < arr[j-1]{ | |
arr[j], arr[j-1] = arr[j-1], arr[j] | |
j-- | |
} | |
} | |
return arr | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment