Created
January 21, 2020 04:27
-
-
Save rahulkushwaha12/a59861ffa5aa1ea21f526ed9ef26cc30 to your computer and use it in GitHub Desktop.
Bubble 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]) | |
} | |
bubbleSort(&arr, 0, n-1) | |
fmt.Println("sorted array ", arr) | |
} | |
func bubbleSort(a *[]int, s, e int) { | |
arr := *a | |
swapped := false | |
for i := s; i < e; i++ { | |
for j := s + 1; j <= e-i; j++ { | |
if arr[j-1] > arr[j] { | |
t := arr[j-1] | |
arr[j-1] = arr[j] | |
arr[j] = t | |
swapped = true | |
} | |
} | |
if !swapped { | |
return | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment