Created
July 17, 2021 04:46
-
-
Save Kailashcj/a8ed7c9e2ecd29a939a76a76b2fe429e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
code tested in leetcode