Created
December 17, 2019 09:03
-
-
Save vegetaz/90e64aa4c1d4ae28206d7b88db91c699 to your computer and use it in GitHub Desktop.
Quick Sort
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 class QuickSort { | |
public static void main(String[] args) { | |
int[] x = {6, 2, 3, 4, 5, 9, 1}; | |
printArray(x); | |
int left = 0; | |
int right = x.length - 1; | |
quickSort(x, left, right); | |
printArray(x); | |
} | |
public static void quickSort(int[] arr, int left, int right) { | |
if (arr == null || arr.length == 0) | |
return; | |
if (left >= right) | |
return; | |
int middle = left + (right - left) / 2; | |
int pivot = arr[middle]; | |
int i = left, j = right; | |
while (i <= j) { | |
while (arr[i] < pivot) { | |
i++; | |
} | |
while (arr[j] > pivot) { | |
j--; | |
} | |
if (i <= j) { | |
int temp = arr[i]; | |
arr[i] = arr[j]; | |
arr[j] = temp; | |
i++; | |
j--; | |
} | |
} | |
if (left < j) | |
quickSort(arr, left, j); | |
if (right > i) | |
quickSort(arr, i, right); | |
} | |
public static void printArray(int[] arr) { | |
for(int i = 0; i < arr.length; i++) { | |
System.out.print(arr[i] + " "); | |
} | |
System.out.println(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment