Skip to content

Commit

Permalink
feat: add implementation of simple sort (TheAlgorithms#395)
Browse files Browse the repository at this point in the history
  • Loading branch information
Crazy3lf authored Oct 20, 2021
1 parent 9cdf346 commit cfd0999
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
35 changes: 35 additions & 0 deletions sort/simplesort.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// simplesort.go
// description: Implementation of a simple sorting algorithm
// details:
// A simple sorting algorithm that look counter intuitive at first glance and very similar to Exchange Sort
// An improved version is included with slight changes to make the sort slightly more efficient
// reference: https://arxiv.org/abs/2110.01111v1
// see sort_test.go for a test implementation, test function TestSimple and TestImprovedSimple

package sort

func SimpleSort(arr []int) []int {
for i := 0; i < len(arr); i++ {
for j := 0; j < len(arr); j++ {
if arr[i] < arr[j] {
// swap arr[i] and arr[j]
arr[i], arr[j] = arr[j], arr[i]
}
}
}
return arr
}

// ImprovedSimpleSort is a improve SimpleSort by skipping an unnecessary comparison of the first and last.
// This improved version is more similar to implementation of insertion sort
func ImprovedSimpleSort(arr []int) []int {
for i := 1; i < len(arr); i++ {
for j := 0; j < len(arr)-1; j++ {
if arr[i] < arr[j] {
// swap arr[i] and arr[j]
arr[i], arr[j] = arr[j], arr[i]
}
}
}
return arr
}
16 changes: 16 additions & 0 deletions sort/sorts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,14 @@ func TestRadix(t *testing.T) {
testFramework(t, RadixSort)
}

func TestSimple(t *testing.T) {
testFramework(t, SimpleSort)
}

func TestImprovedSimple(t *testing.T) {
testFramework(t, ImprovedSimpleSort)
}

// Very slow, consider commenting
// func TestSelection(t *testing.T) {
// testFramework(t, SelectionSort)
Expand Down Expand Up @@ -298,6 +306,14 @@ func BenchmarkRadix(b *testing.B) {
benchmarkFramework(b, RadixSort)
}

func BenchmarkSimple(b *testing.B) {
benchmarkFramework(b, SimpleSort)
}

func BenchmarkImprovedSimple(b *testing.B) {
benchmarkFramework(b, ImprovedSimpleSort)
}

// Very Slow, consider commenting
func BenchmarkSelection(b *testing.B) {
benchmarkFramework(b, SelectionSort)
Expand Down

0 comments on commit cfd0999

Please sign in to comment.