6
\$\begingroup\$

Learning Go and trying to get a grip of the various concepts it uses. Following is my implementation of Quicksort (choosing last element as pivot). It takes the length of the array and the subsequent array to be sorted as user input.

package main
import "fmt"
func main() {
 var n int
 fmt.Print("Enter Size: ")
 fmt.Scan(&n)
 var slice = make([]int, n)
 for i := 0; i < n; i++ {
 fmt.Print("arr[",i,"]: ")
 fmt.Scan(&slice[i])
 }
 fmt.Print("Array: ", slice, "\n")
 quickSort(slice, 0, n - 1)
 fmt.Print("Sorted Array: ", slice)
}
func quickSort(a []int, low int, high int) {
 if(low < high) {
 p := partition(a, low, high)
 quickSort(a, low, p - 1)
 quickSort(a, p + 1, high)
 }
}
func partition(a []int, low int, high int) int {
 pivot := a[high]
 i := low
 for j := low; j < high; j++ {
 if(a[j] <= pivot) {
 swap(&a[i], &a[j])
 i += 1
 }
 }
 swap(&a[i], &a[high])
 return i
}
func swap(a, b *int) {
 temp := *a
 *a = *b
 *b = temp
}

Comments on coding style, following/avoiding language convention, use of pointers, use of slices, and overall correctness of the program will be appreciated.

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Jun 23, 2016 at 9:04
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

Most importantly, use slices to your advantage. You do not need high and low arguments, as a slice can represent a part of a slice. For example, instead of quickSort(a, low, p - 1) you could write quickSort(a[low:p]).

Swapping can be written much more elegantly with multiple assignment: a, b = b, a

Use fmt.Printfln instead of fmt.Print("Array: ", slice, "\n"). Once you have learned printf, it is almost always clearer than concatenating strings. In this simple case fmt.Println would be appropriate as well, though.

Other than that the code is clean. It seems you have used gofmt and using int instead of uint for indices is the correct choice. (Uint should only be used where absolutely needed, because it is inconvenient and error-prone to calculate with.)

answered Jul 1, 2016 at 17:53
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.