Created
January 20, 2020 17:37
-
-
Save rahulkushwaha12/f136993e2f772aae39634a53af678f23 to your computer and use it in GitHub Desktop.
Insertion Sort in go
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" | |
) | |
/* | |
5 | |
25, 17, 31, 13, 2 | |
sorted array [2 13 17 25 31] | |
Worst Case Time Complexity [ Big-O ]: O(n2) | |
Best Case Time Complexity [Big-omega]: O(n) | |
Average Time Complexity [Big-theta]: O(n2) | |
*/ | |
func main() { | |
var n int | |
fmt.Println("enter the no of inputs") | |
fmt.Scanln(&n) | |
arr := make([]int, n) | |
fmt.Println("enter the numbers >") | |
for i := 0; i < n; i++ { | |
fmt.Scan(&arr[i]) | |
} | |
for i := 1; i < n; i++ { | |
valToInsert := arr[i] | |
k := i | |
for k > 0 && arr[k-1] > valToInsert { | |
arr[k] = arr[k-1] | |
k-- | |
} | |
if k != i { | |
arr[k] = valToInsert | |
} | |
} | |
fmt.Println("sorted array ", arr) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment