selection sort added

pull/2/head
0xAX 10 years ago
parent e3e85e81bb
commit 6354c6d109

@ -12,6 +12,14 @@ usage
3. Execute `go build bubble_sort.go` and `./bubble_sort`
alghoritms
----------
#### Sorting
* bubble sort
* selection sort
todo
------

@ -1,15 +1,7 @@
package main
/*
* Bubble sort, sometimes referred to as sinking sort,
is a simple sorting algorithm that works by repeatedly
stepping through the list to be sorted, comparing
each pair of adjacent items and swapping them if
they are in the wrong order. The pass through
the list is repeated until no swaps are needed,
which indicates that the list is sorted.
Complexity - О(n2)
* Bubble sort - http://en.wikipedia.org/wiki/Bubble_sort
*/
import "fmt"
@ -17,21 +9,21 @@ import "fmt"
import "github.com/IoSync/go-alghoritms"
func main() {
arr := utils.RandArray(10)
fmt.Println("Initial array is:", arr)
fmt.Println("")
tmp := 0
for i := 0; i < len(arr); i++ {
for j := 0; j < len(arr) - 1; j++ {
if arr[j] > arr[j + 1] {
tmp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = tmp
}
}
}
fmt.Println("Sorted array is: ", arr)
arr := utils.RandArray(10)
fmt.Println("Initial array is:", arr)
fmt.Println("")
tmp := 0
for i := 0; i < len(arr); i++ {
for j := 0; j < len(arr) - 1; j++ {
if arr[j] > arr[j + 1] {
tmp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = tmp
}
}
}
fmt.Println("Sorted array is: ", arr)
}

@ -1,7 +1,33 @@
package main
/*
* Selection sort - http://en.wikipedia.org/wiki/Selection_sort
*/
import "fmt"
import "github.com/IoSync/go-alghoritms"
func main() {
fmt.Println("")
arr := utils.RandArray(10)
fmt.Println("Initial array is:", arr)
fmt.Println("")
var min int = 0
var tmp int = 0
for i := 0; i < len(arr); i++ {
min = i
for j := i + 1; j < len(arr); j++ {
if arr[j] < arr[min] {
min = j
}
}
tmp = arr[i]
arr[i] = arr[min]
arr[min] = tmp
}
fmt.Println("Sorted array: ", arr)
}

@ -3,11 +3,11 @@ package utils
import "math/rand"
func RandArray(n int) []int {
arr := make([]int, n)
for i := 0; i <= n - 1; i++ {
arr[i] = rand.Intn(n)
}
return arr
arr := make([]int, n)
for i := 0; i <= n - 1; i++ {
arr[i] = rand.Intn(n)
}
return arr
}

Loading…
Cancel
Save