Javascript快速排序演算法詳解_基礎知識

來源:互聯網
上載者:User

快速排序是對冒泡排序的一種改進。通過一趟排序將要排序的資料分割成獨立的兩部分,其中一部分的所有資料都比另外一部分的所有資料都要小,然後再按此方法對這兩部分資料分別進行快速排序,整個排序過程可以遞迴進行,最終達到整個資料變成有序序列。

假設要排序的數組是A[0]……A[N-1],首先任意選取一個資料(通常選用數組的第一個數)作為基準資料,然後將所有比它小的數都放到它前面,所有比它大的數都放到它後面,這個過程稱為一趟快速排序。值得注意的是,快速排序不是一種穩定的排序演算法,也就是說,多個相同的值的相對位置也許會在演算法結束時產生變動。
一趟快速排序的演算法是:
1)設定兩個變數low、high,排序開始的時候:low=0,high=N-1;
2)以第一個數組元素作為基準資料,賦值給base,即base=A[0];
3)從high開始向前搜尋,即由後開始向前搜尋(high--),找到第一個小於base的值A[high],將A[high]和A[low]互換;
4)從low開始向後搜尋,即由前開始向後搜尋(low++),找到第一個大於base的A[low],將A[low]和A[high]互換;
5)重複第3、4步,直到low=high;

複製代碼 代碼如下:

function partition(elements, low, high){
  //預設將左側首元素作為基準元素
  var base=elements[low];
  while(low < high){
    //從後往前搜尋,直到找到比基準元素小的元素,並進行交換
    while(low < high && elements[high] >= base) high--;
    var swap1=elements[low];elements[low]=elements[high];elements[high]=swap1;
    //從前往後搜尋,直到找到比基準元素大的元素,並進行交換
    while(low < high && elements[low] <= base) low++;
    var swap2=elements[low];elements[low]=elements[high];elements[high]=swap2;
  }
  //返回基準元素的位置,作為序列的分割位置
  return low;
}
function sort(elements, low, high){
  if(low<high){
    //將序列一分為二,分為分割位置的前後序列,前序列比分割位置的值小,後序列比分割位置的值大
    var partitionPos=partition(elements, low, high);
    //對前序列繼續遞迴排序
    sort(elements, 0, partitionPos-1);
    //對後序列繼續遞迴排序
    sort(elements, partitionPos+1, high);
  }
}
var elements = [3, 1, 5, 7, 2, 4, 9, 6, 10, 8];
console.log('before: ' + elements);
sort(elements, 0, elements.length-1);
console.log(' after: ' + elements);

效率:

時間複雜度:最好:O(nlog2n),最壞:O(n^2),平均:O(nlog2n)。

空間複雜度:O(nlog2n)。

穩定性:不穩定。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.