public class QuickSort {
public static void main(String[] args) {
int[] arr = {7,3,2,8,1,9,5,4,6,0,11};
sort(arr, 0, arr.length-1);
print(arr);
}
static void sort(int[] arr, int leftBound, int rightBound) {
if (leftBound >= rightBound) return;
int mid = partition(arr, leftBound, rightBound);
sort(arr, leftBound, mid-1);
sort(arr, mid+1, rightBound);
}
static int partition(int[] arr, int leftBound, int rightBound) {
int i = leftBound;
int j = rightBound-1;
int pivot = arr[rightBound];
while (i<=j) {
while (arr[i] <= pivot && i<=j) i++;
while (arr[j] > pivot && i<=j) j--;
if (i<j) swap(arr, i, j);
}
swap(arr, rightBound, i);
return i;
}
static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static void print(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
快速排序 QuickSort
最新推荐文章于 2024-08-07 13:51:12 发布