数据结构学习(十三)、快速排序
生活随笔
收集整理的這篇文章主要介紹了
数据结构学习(十三)、快速排序
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
基本思想:通過一趟排序將待排記錄分割成獨立兩個部分,其中一部分記錄的關鍵字均比另一部分記錄的關鍵字小,
則可分別對這兩部分繼續進行排序,重復操作以上操作,已達到整個序列有序的目的
void QuickSort(SqList *L){QSort(L,1,L->length);} /* 對順序表L中的子序列L->dara[low..high]最快速排序 */void QSort(SqList *L,int low,int high) { int pivot; if(low<high){ pivot = Partition(L,low,high); /*將L->data[low..high]一分為二,并算出分界點 */ QSort(L,low,pivot-1); /* 分界點左邊進行排序 */ QSort(L,pivot+1,high); /* 分界點右邊進行排序 */ } } /*
交換L中子表的記錄,使樞軸記錄到位,并返回其所在的位置
此時,它之前(后)的記錄均不大(小)于它
*/int Partition(SqList *L,int low,int high) { int pivotkey; pivotkey = L->r[low]; while(low<high){ while(low<high && L->r[high]>=pivotkey) high --; swap(L,low,high); while(low<high && L->r[low]<=pivotkey) low++; swap(L,low,high); } return low; } ?改進算法:
1、優化選取樞軸
? 三數取中法,即先選取三個關鍵字進行排序,將中間數作為樞軸,一般取左端、中間、右端三個數。
/* 交換L中子表的記錄,使樞軸記錄到位,并返回其所在的位置 此時,它之前(后)的記錄均不大(小)于它 */int Partition(SqList *L,int low,int high){int pivotkey;int m = low +(high-low)/2; /* 計算數組中間元素的下標 */if(L->data[low]>L->data[high]) /* 交換左右保證左邊的較小 */swap(L,low,high);if(L->data[m]>L->data[high]) /* 交換中間 和右邊保證中間的較小 */swap(L,m,high);if(L->data[low]>L->data[m]) /* 交換中間 和左邊保證左邊的較小 */swap(L,m,low);pivotkey = L->data[m]; /* 用子表的中間值作為樞軸 */L->data[0] = pivotkey; /* 將軸關鍵字備份到L->data[0] */while(low<high){while(low<high && L->data[high]>=pivotkey)high --;L->data[low] = L->data[high]; /* 采用替換 而不采用交換 */while(low<high && L->data[low]<=pivotkey)low++;L->data[high] = L->data[low]; /* 采用替換 而不采用交換 */}L->data[low] = L->data[0]; /* 將樞軸數值替換回L->data[low] */return low;}
?
? 優化不必要的交換
轉載于:https://www.cnblogs.com/huixuexidezhu/p/5969200.html
總結
以上是生活随笔為你收集整理的数据结构学习(十三)、快速排序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 多囊卵巢综合症的预防
- 下一篇: 简单查询