快速排序算法跟冒泡排序类似,都是基于交换排序的思想,快速排序是对冒泡排序的改进。
快速排序通过多次比较和交换实现排序,其排序流程如下:
(1)首先设置一个分界值,通过该分界值将数组分为左右连部分。
(2)将大于等于分界值得数据集中到数组右边,小于分界值得移动左边。
(3)对左右两边继续取分界值,移动数据。
(4)重复上述过程,可以看出这是一个递归定义。通过递归将左侧数据排好序后在递归右侧数据,直到整个数组排序完成。
代码如下:
public class quickSort {
static void quickSort(int[] arr,int left,int right) //快速排序算法
{
int f,t;
int rtemp,ltemp;
ltemp=left;
rtemp=right;
f=arr[(left+right)/2]; //分界值
while(ltemp<=rtemp)
{
while(arr[ltemp]<f)
{
++ltemp;
}
while(arr[rtemp]>f)
{
--rtemp;
}
if(ltemp<=rtemp)
{
t=arr[ltemp];
arr[ltemp]=arr[rtemp];
arr[rtemp]=t;
--rtemp;
++ltemp;
}
}
if(ltemp==rtemp)
{
ltemp++;
}
if(left<rtemp)
{
quickSort(arr,left,ltemp-1); //递归调用
}
if(ltemp<right)
{
quickSort(arr,rtemp+1,right); //递归调用
}
}
public static void main(String[] args){
int a[] ={8,5,9,5,7,1,3,7,5} ;
quickSort(a, 0, a.length-1);
for(int i = 0;i<a.length;i++)
System.out.print(a[i]);
}
}
快速排序的算法可以优化,中间值的选取直接影响了,快速排序的效率。