快速排序算法

来源:互联网 发布:淘宝店铺彻底释放 编辑:程序博客网 时间:2024/06/05 06:43
/* date:2014.12.14
快速排序思路:和冒泡排序相似,基于比较和交换来实现排序,改进后效率高了。
流程:1).首先设置一个分界值,通过该值将数组分成左右两部分,左边序列小于等于它,右边序列大于等于它;
            2).对于左边和右边的序列,分别执行(1)操作;
            3).重复(2),相当于递归,直到有序。
时间复杂度:最差O(n^2),平均O(nlogn).
空间复杂度:O(log2(n))-O(n).
是一种 不稳定 的排序算法.
*/
 
void QuickSort(int *arr,int left,int right)
{
int key,temp,ltemp,rtemp;

ltemp = left;
rtemp = right;
key=arr[(left + right) / 2];

while (ltemp <= rtemp)
{
while (arr[ltemp] < key)
{
ltemp ++;
}
while (key < arr[rtemp])
{
rtemp --;
}
if (ltemp <= rtemp)
{
temp = arr[ltemp];
arr[ltemp] = arr[rtemp];
arr[rtemp] = temp;
ltemp ++;
rtemp --;
}
}

if (left < rtemp)
{
QuickSort(arr,left,rtemp);
}
if (ltemp < right)
{
QuickSort(arr,ltemp,right);
}
/* //用以下代码也可
if (left < rtemp)
{
QuickSort(arr,left,ltemp - 1);
}
if (ltemp < right)
{
QuickSort(arr,rtemp + 1,right);
}*/

}



0 0
原创粉丝点击