Created
June 27, 2022 14:49
-
-
Save zhangr4/28a9904ac4c0b761dfd6f6b9a40a2787 to your computer and use it in GitHub Desktop.
quick sort_example
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[] test = new int[]{5,1,1,2,0,0}; | |
quickSortArr(test, 0, test.length-1); | |
printArr(test); | |
} | |
public static void printArr(int[] arr) { | |
System.out.println("test"); | |
for(int i = 0; i < arr.length; i++) { | |
System.out.print(arr[i] + ", "); | |
} | |
System.out.println(); | |
} | |
public static void quickSortArr(int[] arr, int l, int r) { | |
if(l >= r) { | |
return; | |
} | |
int begin = l, end = r; | |
int pivot = arr[begin]; | |
while(begin < end) { | |
while(begin < end && arr[end] >= pivot) { // !!! if use arr[end] > pivot the recycle would not end | |
end--; | |
} | |
if( begin < end) { | |
arr[begin] = arr[end]; | |
} | |
while(begin < end && arr[begin] <= pivot) { | |
begin++; | |
} | |
if(begin < end) { | |
arr[end] = arr[begin]; | |
} | |
} | |
arr[begin] = pivot; | |
quickSortArr(arr, l, begin); | |
quickSortArr(arr, begin+1, r); | |
return; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment