快速排序算法策略
- 分解:選擇數組a中的一個元素q作爲基準,把數組劃分爲三段a1<q,a2=q和a3>q。
- 遞歸:對數組a1,a2遞歸調用快速排序算法。
- 合併:不需要額外操作
快速排序法時間複雜度分析
1、最優情況
每次都剛好在中間。
解遞歸方程得:
2、最壞情況
解遞歸方程得:
3、平均情況
算法圖解
第一步:
1、選擇第一個元素41作爲標準。
2、指針i從左邊開始尋找比41大的元素,找到67。
3、指針j從右邊尋找比41小的元素,找到24。
4、交換24和67,繼續尋找,直到i>j,跳出循環。
5、交換41和j當前指向的元素0.
第二步:
1、41的位置已經正確。
2、對數組0、24、34和69、67、78、58、62、64按照第一步的方法排序。
第三步:
1、0、41、69、78的位置正確。
2、對24、34和67、64、58進行排序
第四步:
1、0、24、34、41、58、62、69、78位置正確。
2、對64、67排序。
算法C++實現
void quicksort(int a[], int q, int r);
int partition(int a[], int q, int r);
void quicksort(int a[], int q, int r)
{
if (q < r)
{
int p = partition(a, q, r);//left part < target | target | right par > target
quicksort(a, q, p - 1);//sort left part
quicksort(a, p + 1, r);//sort right part
}
}
int partition(int a[], int q, int r)
{
int i = q;
int j = r;
int target = a[q];
while (true)
{
i++;
while (a[i] < target && i < r)//Find a[i] >= target
{
i++;
}
while (a[j] > target)//Find a[j] <= target
{
j--;
}
if (i >= j) break;
int temp = a[j];//Swap a[i], a[j]
a[j] = a[i];
a[i] = temp;
}
int temp = a[j];//Swap a[j], target
a[j] = a[q];
a[q] = temp;
return j;
}
void main()
{
#define length 10 //Length of the original array
int a[length] = {};
int b[length] = {};
for (int i = 0; i < length; i++)//Generate the original array
{
a[i] = rand() % 100;
}
for (int i = 0; i < length; i++)//print the original array
{
cout << a[i] << " ";
}
cout << endl;
quicksort(a,0, length-1);//sort the array
for (int i = 0; i < length; i++)//print the sorted array
{
cout << a[i] << " ";
}
system("pause");
}
運行結果如下