演算法筆記之快速排序,演算法筆記之排序
1.1演算法思路——
該演算法在數組中選定一個元素作為主元(一般選第一個),然後以這個主元為參考對象將數組分為兩個部分,第一部分都是小於或者等於主元,第二部分都是大於或者等於主元。然後對第一和第二部分遞迴地使用快速排序演算法,直到分到最小的小組為止。
1.2時間複雜度——
在最差的情況下,要把n個元素的數組劃分,需要n次比較和n次移動。假設用T(n)來表示使用快速排序演算法來排序n個元素的數組所耗費的時間。那麼
T(n) = T(n/2)+ T(n/2) +2n
所以,快速排序的時間複雜度應該是 T(n) =O(nlogn)。
1.3程式流程圖
1.4實現代碼
package lin.algo;public class QuickSort {int[] list;public QuickSort(int[] list){this.list = list;}public int[] quickSort(){quick(list,0,list.length-1);return list;}private void quick(int[] list,int first , int last){if (last>first) {int pivoxIndex = partition(list, first, last);quick(list, first, pivoxIndex-1);quick(list, pivoxIndex+1, last);}}/** * 根據第一個元素來劃分數組 * 輸入的是要劃分的原始數組,第一個元素下標和最後一個元素下標 * @param list * @param first * @param last * @return 分組後的主元下標 */private int partition(int[] list,int first , int last){//主元int privot = list[first];int secondIndex = first+1;int lastIndex = last;//遍曆查詢,大於主元的在右邊,小於的在左邊//實現方法:兩邊查起,將左邊大於主元的與右邊小於主元的交換,//最後把主元放在兩個分好組的中間位置while(lastIndex>secondIndex){//尋找左邊第一個比主元大的while(secondIndex<= lastIndex &&list[secondIndex]<=privot ){secondIndex++;}//尋找右邊第一個比主元小的while( secondIndex<= lastIndex && list[lastIndex]> privot){lastIndex--;}//至此,如果還沒檢查完序列,就證明分別找到了,交換if (secondIndex< lastIndex) {int temp = list[secondIndex];list[secondIndex] = list[lastIndex];list[lastIndex] = temp;}}while(list[lastIndex] >= privot && lastIndex> first){lastIndex --;}//返回主元新下標if (privot > list[lastIndex]) {list[first] = list[lastIndex];list[lastIndex] = privot;return lastIndex;}else {return first;}}}
快速排序的演算法實現
#include <stdio.h>
int partions(int l[],int low,int high)
{
int prvotkey=l[low];
l[0]=l[low];
while (low<high)
{
while (low<high&&l[high]>=prvotkey)
--high;
l[low]=l[high];
while (low<high&&l[low]<=prvotkey)
++low;
l[high]=l[low];
}
l[low]=l[0];
return low;
}
void qsort(int l[],int low,int high)
{
int prvotloc;
if(low<high)
{
prvotloc=partions(l,low,high); //將第一次排序的結果作為樞軸
qsort(l,low,prvotloc-1); //遞迴調用排序 由low 到prvotloc-1
qsort(l,prvotloc+1,high); //遞迴調用排序 由 prvotloc+1到 high
}
}
void quicksort(int l[],int n)
{
qsort(l,1,n); //第一個作為樞軸 ,從第一個排到第n個
}
void main()
{
int a[11]={0,2,32,43,23,45,36,57,14,27,39};
for (int b=1;b<11;b++)
printf("%3d",a[b]);
printf("\n");
quicksort(a,11);
for(int c=1;c<11;c++)
printf("%3d",a[c]);
}
編寫一個演算法,實現快速排序
/************************************************************************/
/* 快速排序 */
/************************************************************************/
void CommonALG::quickSort(float *arr, int left, int right)
{
int ltemp = left;
int rtemp = right;
float f = arr[(left + right) / 2];
float t = 0;
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);
}