Created
November 9, 2020 04:44
-
-
Save shahzadaazam/8a01ef085d783005ce351fa63faf4b78 to your computer and use it in GitHub Desktop.
Quicksort recursive implementation
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
class Quicksort { | |
public static void main(String[] args) { | |
int[] arr = new int[]{4, 6, 2, 3, 5, 8, 9, 1}; | |
quicksort(arr, 0, arr.length-1); | |
printArr(arr); | |
} | |
public static void quicksort(int[] arr, int left, int right) { | |
if (left < right) { | |
int pivot = arr[(left + right)/2]; | |
int index = partition(arr, left, right, pivot); | |
quicksort(arr, left, index-1); | |
quicksort(arr, index, right); | |
} | |
} | |
private static int partition(int[] arr, int left, int right, int pivot) { | |
while(left <= right) { | |
while(arr[left] < pivot) { | |
left++; | |
} | |
while(arr[right] > pivot) { | |
right--; | |
} | |
if (left <= right) { | |
swap(arr, left, right); | |
left++; | |
right--; | |
} | |
printArr(arr); | |
} | |
return left; | |
} | |
private static void swap(int[] arr, int left, int right) { | |
int temp = arr[left]; | |
arr[left] = arr[right]; | |
arr[right] = temp; | |
} | |
private static void printArr(int[] arr) { | |
for(int num : arr) { | |
System.out.print(num + ", "); | |
} | |
System.out.println(""); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment