move bubble_sort and other sortings to separate packages

Signed-off-by: Alexander Kuleshov <kuleshovmail@gmail.com>
move-sorts-to-separate-packages
Alexander Kuleshov 6 years ago
parent 8a8ce96014
commit 745435d087
No known key found for this signature in database
GPG Key ID: EE88CAC52D66AC9B

@ -0,0 +1,17 @@
package bubble_sort
import (
sortable "github.com/0xAX/go-algorithms/sort"
)
func Sort(data sortable.Sortable) sortable.Sortable {
for i := 0; i < data.Len()-1; i++ {
for j := 0; j < data.Len()-i-1; j++ {
if data.Less(j+1, j) {
data.Swap(j, j+1)
}
}
}
return data
}

@ -0,0 +1,25 @@
package bubble_sort
import (
sortable "github.com/0xAX/go-algorithms/sort"
"math/rand"
"testing"
)
func TestSort(t *testing.T) {
var s = make(sortable.IntSlice, 10)
for i := 0; i < 10; i++ {
s[i] = rand.Intn(i + 1)
}
Sort(&s)
for i := 0; i < 10; i++ {
if i != 9 {
if s[i] > s[i+1] {
t.Fatal("s[i] > s[i + 1]", s[i], s[i+1])
}
}
}
}

@ -0,0 +1,30 @@
package sort
type Sortable interface {
// Len is the number of elements in the collection.
Len() int
// Less reports whether the element with
// index i should sort before the element with index j.
Less(i, j int) bool
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
}
type IntSlice []int
func (s IntSlice) Len() int {
return len(s)
}
func (s IntSlice) Less(i, j int) bool {
if s[i] < s[j] {
return true
}
return false
}
func (s IntSlice) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}

@ -1,29 +0,0 @@
package main
/*
* Bubble sort - http://en.wikipedia.org/wiki/Bubble_sort
*/
import "fmt"
import "github.com/0xAX/go-algorithms"
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-i; 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)
}
Loading…
Cancel
Save