Created
December 21, 2014 20:24
-
-
Save arjunrao87/335067bf90bd376cb9a5 to your computer and use it in GitHub Desktop.
Quicksort algorithm
This file contains 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
public void quickSort(int[] array) { | |
quickSort(array, 0, array.length - 1); | |
} | |
public void quickSort(int[] array, int left, int right) { | |
int pivotIndex = partition(array, left, right); | |
if (left < pivotIndex - 1) { | |
quickSort(array, left, pivotIndex - 1); | |
} | |
if (right > pivotIndex) { | |
quickSort(array, pivotIndex, right); | |
} | |
} | |
public static int partition(int[] array, int left, int right) { | |
int pivot = array[left+ (right-left)/2]; | |
while (left <= right) { | |
while (array[left] < pivot) { | |
left++; | |
} | |
while (array[right] > pivot) { | |
right--; | |
} | |
if (left <= right) { | |
int tmp = array[left]; | |
array[left] = array[right]; | |
array[right] = tmp; | |
left++; | |
right--; | |
} | |
} | |
return left; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment