Skip to content

Commit

Permalink
feat: some concurrency tryout
Browse files Browse the repository at this point in the history
  • Loading branch information
aholbreich committed Nov 11, 2024
1 parent ead81c5 commit 3a0f939
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
40 changes: 40 additions & 0 deletions sorting/quicksort.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ Complexity of O(n log n) and a worst-case complexity of O(n^2).
*/
package sorting

import "sync"

// Idiomatic implementation, uses slices. Turns out to have best performance!
func IdiomaticQuickSort(arr []int) []int {
if len(arr) < 2 {
Expand All @@ -32,3 +34,41 @@ func IdiomaticQuickSort(arr []int) []int {
}
return append(IdiomaticQuickSort(right), IdiomaticQuickSort(left)...)
}

// TODO, too much overhead in this implementation.
func ConcurrentQuickSort(arr []int) []int {
if len(arr) < 2 {
return arr
}

pivot := arr[len(arr)/2]

var left, right []int
for _, element := range arr {
if element <= pivot {
right = append(right, element)
} else {
left = append(left, element)
}
}

var leftSorted, rightSorted []int
var wg sync.WaitGroup

wg.Add(1)
go func() {
defer wg.Done()
leftSorted = ConcurrentQuickSort(left)
}()

wg.Add(1)
go func() {
defer wg.Done()
rightSorted = ConcurrentQuickSort(right)
}()

wg.Wait() //blocks here util counter is back to 0

// Concatenate leftSorted, pivot, and rightSorted
return append(rightSorted, leftSorted...)
}
15 changes: 15 additions & 0 deletions sorting/quicksort_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,21 @@ func TestIdiomaticQuickSort(t *testing.T) {
}
}

func TestConcurrentQuickSort(t *testing.T) {

testArray := getSamples(false)
expected := getSamples(true)

start := time.Now()
var result = ConcurrentQuickSort(testArray)
elapsed := time.Since(start)

fmt.Printf("ConcurrentQuickSort: Time for %d elements %s ", arraySize, elapsed)
if !reflect.DeepEqual(result, expected) {
t.Errorf("ConcurrentQuickSort failed. Got %v, expected %v", result, expected)
}
}

// samples helper
func getSamples(increasing bool) []int {
result := make([]int, arraySize)
Expand Down

0 comments on commit 3a0f939

Please sign in to comment.