Created
February 27, 2019 02:16
-
-
Save ndkhoa/06bf474bd38942870a33843c25c8a43b to your computer and use it in GitHub Desktop.
Bubble Sort
This file contains hidden or 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 BubbleSort(array []int) []int { | |
| endIndex := len(array) | |
| var flag, counter int | |
| // Cach 1 | |
| // counter = 0 | |
| // for i := 0; i < endIndex; i++ { | |
| // for j := 1; j < endIndex-i; j++ { | |
| // counter++ | |
| // if array[j-1] > array[j] { | |
| // array[j-1], array[j] = array[j], array[j-1] | |
| // } | |
| // } | |
| // } | |
| // Cach 2 | |
| for i := 0; i < endIndex; i++ { | |
| flag = 0 | |
| for j := 1; j < endIndex-i; j++ { | |
| counter++ | |
| if array[j-1] > array[j] { | |
| array[j-1], array[j] = array[j], array[j-1] | |
| flag = 1 | |
| } | |
| } | |
| if flag == 0 { | |
| break | |
| } | |
| } | |
| fmt.Printf("counter: %v\n", counter) | |
| fmt.Println(array) | |
| return array | |
| } | |
| func main() { | |
| BubbleSort([]int{5, 1, 4, 2, 8}) | |
| fmt.Println() | |
| BubbleSort([]int{5, 1, 4, 7, 8}) | |
| fmt.Println() | |
| BubbleSort([]int{1, 2, 3, 4, 5}) | |
| } |
This file contains hidden or 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
| def bubble_sort(array) | |
| counter = 0 | |
| for index in 0...array.size | |
| puts array[index] | |
| end | |
| # puts "counter: #{counter}" | |
| # puts array.join(' ') | |
| end | |
| bubble_sort([5, 1, 4, 2, 8]) | |
| puts | |
| bubble_sort([5, 1, 4, 7, 8]) | |
| puts | |
| bubble_sort([1, 2, 3, 4, 5]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment