//快速排序就是以一个基准值为标准,将一个待排序的数组分为比它大和比它小的两部分。
public class QuickSort {
public static void main(String[] args) {
int a[]={34,65,87,23,12,21,87,98,11,34,45,67,98};
System.out.println(Arrays.toString(achieveQuickSort(a,0,a.length-1)));
}
public static int[] achieveQuickSort(int a[],int first,int last){
int start =first;
int end =last;
int standardValue=a[first];
while(end>start){
//从后向前走,如果比基准值小就交换位置,否则end--
while(end>start&&a[end]>=standardValue) end--;
if(standardValue>a[end]){
int temp=a[end];
a[end]=a[start];
a[start]=temp;
}
//从前向后走,如果比基准值大就交换位置,否则start++
while(end>start&&standardValue>=a[start]) start++;
if(a[start]>standardValue){
int temp=a[start];
a[start]=a[end];
a[end]=temp;
}
}
//此时start和end是相等的。
if(start>first) achieveQuickSort(a,first,start-1);
if(end<last) achieveQuickSort(a,start+1,last);
return a;
}
}
快速排序 java实现
最新推荐文章于 2024-10-06 20:16:20 发布