Spearfisher
Spearfisher

Reputation: 8783

Quicksort implementation in Go

I am trying to implement a quicksort algorithm in go just for learning purposes.

So far I have come up with the following code:

package main

import (
    "fmt"
)

var arr = []int{20, 43, 52, -1, 43, 29, 34}

func main() {
    fmt.Println("Unsorted: ", arr)
    quick_sort(arr)
    fmt.Println("Sorted: ", quick_sort(arr))
}

func quick_sort(arr []int) []int {
    var recurse func(left int, right int)
    var swap func(i int, j int)
    var partition func(left int, right int, pivot int) int

    swap = func(i int, j int) {
        var temp = arr[i]
        arr[i] = arr[j]
        arr[j] = temp
    }

    partition = func(left int, right int, pivot int) int {
        v := arr[pivot]
        right--
        swap(pivot, right)

        for i := left; i < right; i++ {
            // arr[i] doesn't seem to be updating here
            fmt.Println(arr, left, right, i, arr[i], v)
            if arr[i] <= v {
                left++
                swap(i, left)
            }
        }

        swap(left, right)
        return left
    }

    recurse = func(left int, right int) {
        if left < right {
            pivot := (right + left) / 2
            pivot = partition(left, right, pivot)
            recurse(left, pivot)
            recurse(pivot+1, right)
        }
    }

    recurse(0, len(arr))
    return arr
}

This is a direct translation of a code I had previously written in javascript:

  function quick_sort(arr) {

  function partition(left, right, pivot) {
    var v = arr[pivot];
    swap(pivot, --right);

    for (var i = left;  i < right; i ++) {
      console.log(arr, left, right, i, arr[i], v);
      if (arr[i] <= v) {
        swap(i, left++);
      }
    }
    swap(left, right);

    return left;
  }

  function swap(i, j) {
    var temp = arr[i];

    arr[i] = arr[j];
    arr[j] = temp;
  }

  function recurse(left, right) {
    if (left < right) {
      var pivot = ~~((left + right) / 2)
      pivot = partition(left, right, pivot);
      recurse(left, pivot);
      recurse(pivot + 1, right);
    }
  }

  recurse(0, arr.length)
  return arr;
}

var arr = [20, 43, 52, -1, 43, 29, 34];

console.log(quick_sort(arr));

It works like a charm in js, but somehow I cannot get it to work in go. For some reason, in my partition function, in my for loop, the value of arr[i] remains constant even when i is changing.

I have spent quite a lot of time trying to figure out what I am doing wrong but I couldn't figure it out.

Does anyone see something I'm missing?

Upvotes: 0

Views: 147

Answers (1)

Alper
Alper

Reputation: 13220

left++ should be after the swap() function as follow

   if arr[i] <= v {         
        swap(i, left)
        left++
    }

After the fix, output is

Unsorted:  [20 43 52 -1 43 29 34]
Sorted:  [-1 20 29 34 43 43 52]

Upvotes: 6

Related Questions