Skip to content

Instantly share code, notes, and snippets.

@Kailashcj
Created July 17, 2021 04:46
Show Gist options
  • Select an option

  • Save Kailashcj/a8ed7c9e2ecd29a939a76a76b2fe429e to your computer and use it in GitHub Desktop.

Select an option

Save Kailashcj/a8ed7c9e2ecd29a939a76a76b2fe429e to your computer and use it in GitHub Desktop.
func main() {
nums := []{13,7,4,9}
quicksort(nums, 0, len(nums)-1)
}
func quicksort(arr []int, lo,hi int) {
if len(arr) < 2 {return}
if lo < hi {
p := partition(arr,lo,hi)
quicksort(arr,lo,p-1)
quicksort(arr,p+1,hi)
}
}
func partition(arr []int, i,j int) int {
pivot := arr[i]
lo := i // store initial position of i into a variable for later swap
for i < j {
for i < j && arr[i] <= pivot {
i++
}
for j >= i && arr[j] >= pivot { //IMP: j >= is the key, I was only using > and it was failing in those conditions where i == j. It was then not allowing j to decrement
j--
}
if i < j {
arr[i],arr[j] = arr[j],arr[i]
}
}
//when j has crossed i, swap the j with pivot and return j as the sorted position of the element
arr[lo],arr[j]=arr[j],arr[lo]
return j
}
@Kailashcj
Copy link
Copy Markdown
Author

code tested in leetcode

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment