package quicksort;
public class QStest {
public int partition(int[] a,int low,int high) //分割數組找到基準數的位置
{
int key=a[low],i=low,j=high;
while(i<j) //當i==j時,說明找到基準數的位置
{
while(i<j && a[j]>=key)
j--;
if(i<j)
a[i++]=a[j]; //使用覆蓋
//swap(a,i++,j); //使用交換方式
while(i<j && a[i]<=key)
i++;
if(i<j)
a[j--]=a[i];
//swap(a,i,j--);
}
a[i]=key; //覆蓋後在i位置上就將key插入就可以了
return i; //返回基準數的位置i
}
public void quicksort(int[] a,int low,int high)
{
int dest=0;
if(low<high)
{
dest=partition(a,low,high); //返回基準數的位置
quicksort(a,low,dest-1); //再對基準數位置左右的子數組進行遞歸,當low==high時,子數組就已經有序了
quicksort(a,dest+1,high); //所有子數組有序之後,就相當於整個數組(即原數組)就有序了
}
}
public void swap(int[] a, int i, int j) {
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
public void print(int[] arr)
{
for(int i=0;i<arr.length;i++)
{
if(i!=arr.length-1)
System.out.print(arr[i]+" ");
else
System.out.println(arr[i]);
}
}
public static void main(String[] args)
{
int[] arr={24,65,70,44,43,98};
QStest qs=new QStest();
qs.quicksort(arr, 0, arr.length-1);
qs.print(arr);
}
}
快速排序
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.