快速排序 javascript實現

來源:互聯網
上載者:User

標籤:

Quicksort(快速排序)

是由 東尼·霍爾 所發展的一種排序。

它比其他的Ο(n log n)演算法更快,

因為它的內部迴圈(inner loop)可以在大部分的架構上很有效率地被實現出來。當然,本文是JavaScript實現。

演算法

排序演算法使用分治法 (Divide and conquer) 把一個序列(list)分為兩個子序列(sub-lists)。

步驟
  1. 從數列中挑出一個元素,稱為“基準” (pivot)。
  2. 重新排序數列,所有元素都比基準值曉得擺放在基準前面,所有元素比基準值大的擺在基準的後面(相同的可以到任一邊)。在這個分區退出之後,該基準就處於數列的中間位置。這個稱為分區(partition)操作
  3. 遞迴地(recursive)把小於基準值元素的子數列和大於基準值元素的子數列排序。

遞迴的最底部情形,是數列的大小是零或一,也就是永遠都已經被排序好了。雖然一直遞迴下去,但是這個演算法總會退出,因為在每次迭代(iteration)中,它至少會把一個元素擺放到它最後的位置去。

代碼

配合實現交換的swap的代碼

1 function swap(items,firstIndex,secondIndex){2     var temp = items[firstIndex];3     items[firstIndex] = items[secondIndex];4     items[secondIndex] = temp;5 }

分區(partition)操作

 1 function partition(items,left,right){ 2     var pivot = items[Math.floor((right+left) / 2)], 3         i     = left, 4         j     = right; 5     while (i < j) { 6         while(items[i] < pivot) { 7             i++; 8         } 9         while (items[j] > pivot) {10             j--;11         }12         if (i <= j) {13             swap(items,i,j);14             i++;15             j--;16         }17     }18     return i;19 }

快排(使用遞迴)

 1 function quickSort(items,left,right) { 2     var index; 3     if (items.length > 1) { 4         index = partition(items, left, right); 5         if (left <index - 1) { 6             quickSort(items, left, index - 1); 7         } 8         if (index < right) { 9             quickSort(items, index, right);10         }11     }12     return items;13 }
小結一下

使用了快排,改變了原數組。如果你使用了上方的代碼,要記得這點啊。。

解決的辦法?

複製原數組?

 

 

 

 

是是是是( 

快速排序 javascript實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.