public class QuickSort {
public void quickSort(int[] arr){
sort(arr,0,arr.length-1);
}
public void sort(int[] arr ,int left ,int right){
if(left<right){
int pivot=partition(arr, left, right);
sort(arr, left, pivot-1);
sort(arr,pivot+1,right);
}
}
public int partition(int[] arr,int left ,int right){
int i = left;
int pivot = arr[right];
for (int j=i;j<right;j++){
if(arr[j]<=pivot){
swap(arr,i,j);
i++;
}
}
swap(arr, i, right);
return i;
}
//交换
public void swap(int[] arr,int i,int j){
int temp =arr[j];
arr[j]= arr[i];
arr[i]=temp;
}
public static void main (String[] args) {
int[] arr = {5, 2, 6, 9, 8,0,3,19};
new QuickSort().quickSort(arr);
System.out.println(Arrays.toString(arr));
}
}
手撕快速排序
最新推荐文章于 2024-08-13 14:59:13 发布