Monday, February 19, 2018

Implementing Quick Sort in Golang

What is Quick Sort?
Quick Sort is a sorting algorithm that known as partition exchange sort.


Time Complexity
In the best/average case it gives a time complexity of O(nlogn) and worst time complexity of O(n^2)


Implementation

package main

import (
    "fmt"
    "sort"
)

func quicksort(a sort.Interface, i, j int) {
    if j > i {    
        left, right := i, j
        pivot := j
        for left <= right {
            for ;a.Less(left, pivot); left++ {}
            for ;a.Less(pivot, right); right-- {}
            if left <= right {
                a.Swap(left, right)
                left++
                right--
            }
        }
        quicksort(a, i, right)
        quicksort(a, left, j)
    }
}

func main() {
    arrToBeSorted := []int{1,3,2,5,4,6,7,9,8,10}
    fmt.Println("Before")
    fmt.Println(arrToBeSorted)
   
    fmt.Println("After")
    quicksort(sort.IntSlice(arrToBeSorted), 0, len(arrToBeSorted)-1)
    fmt.Println(arrToBeSorted)
}

Result:




Other Topics:





No comments:

Post a Comment