您的位置:首页 > 理论基础 > 数据结构算法

数据结构&算法学习笔记: 快速排序

2018-02-22 11:20 555 查看
时间复杂度:

最坏:O(n^2)

平均: O(nlogn)

int Partition(int L[], int low, int high)//对子表进行一趟排序,返回枢轴位置
{//L[0]闲置或用作哨兵单元
L[0] = L[low];
int pivotkey = L[low];
while(low < high)
{
while(low < high && L[high] >= pivotkey) --high;
L[low] = L[high];
while(low < high && L[low] <= pivotkey) ++low;
L[high] = L[low];
}
L[low] = L[0];
return low;
}
void Qsort(int L[], int low, int high)
{//L[0]闲置,调用前置初值 low = 1, high = L的length;
if(low < high)
{
int pivotloc = Partition(L, low ,high);//pivotloc是枢轴位置
Qsort(L, low, pivotloc - 1);
Qsort(L, pivotloc + 1, high);
}
}


如果L[0]上面有数字(不闲置),稍微改动一下就可以了

int Patition(int L[], int low, int high)
{
int temp = L[low];
while(low < high)
{
int pivotkey = L[low];
while(low < high && L[high] >= pivotkey)high--;
L[low] = L[high];
while(low < high && L[low] <= pivotkey)low++;
L[high] = L[low];
}
L[low] = temp;
return low;
}

void Qsort(int L[], int low, int high)
{//调用前置low = 0, high = L.length - 1
if(low < high)
{
int pivotloc = Patition(L, low, high);
Qsort(L, low, pivotloc - 1);
Qsort(L, pivotloc + 1, high);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: