堆排序演算法---《程式員必須知道的10大基礎實用演算法及其講解》

來源:互聯網
上載者:User

標籤:http   os   io   art   for   cti   

>

原帖地址:http://www.oschina.net/question/1397765_159365

快速排序演算法的基本特性:

時間複雜度:O(N * logN)

堆排序為不穩定排序,不適合記錄較少的排序。

var arr = [],count = 100,i = 0,parentIndex,exeCount = 0,startTime = + new Date(),stackSort = function(a){if(a.length === 1) return a;var sorted,len,tmpLen;// 構建小頂堆for(len = tmpLen = a.length;len--;){parentIndex = len % 2 === 0 ? len / 2 - 1 :  //右子節點(len - 1) / 2; //左子節點parentIndex < 0 && ( parentIndex = 0 );if(a[len] < a[parentIndex]){a[parentIndex] = [ a[len], a[len] = a[parentIndex] ] [0]; // 交換數組中2個數}}sorted = [ a.shift() ];exeCount++;return sorted.concat( stackSort(a) );};// 構建隨機數組for(;i<count;i++){arr.push( Math.round(Math.random() * count) ); // 0 - count}console.log(‘原來的數組:‘, arr);arr = stackSort(arr);console.log(‘排序後的數組:‘, arr);console.log(‘計算的次數:‘ + exeCount );console.log(‘花費的毫秒數:‘ + (new Date() - startTime) );



聯繫我們

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