插入排序 (Insert Sort)

來源:互聯網
上載者:User

Wiki : http://en.wikipedia.org/wiki/Insertion_sort

看看下面的動態圖片, 就明白插入排序是怎麼回事了:

WiKi上給出的虛擬碼:

Pseudocode of the complete algorithm follows, where the arrays arezero-based:

 // The values in A[i] are checked in-order, starting at the second one for i ← 1 to i ← length(A)-1   {     // at the start of the iteration, A[0..i-1] are in sorted order     // this iteration will insert A[i] into that sorted order      // save A[i], the value that will be inserted into the array on this iteration     valueToInsert ← A[i]     // now mark position i as the hole; A[i]=A[holePos] is now empty     holePos ← i     // keep moving the hole down until the valueToInsert is larger than      // what's just below the hole or the hole has reached the beginning of the array     while holePos > 0 and valueToInsert < A[holePos - 1]       { //value to insert doesn't belong where the hole currently is, so shift          A[holePos] ← A[holePos - 1] //shift the larger value up         holePos ← holePos - 1       //move the hole position down       }     // hole is in the right position, so put valueToInsert into the hole     A[holePos] ← valueToInsert     // A[0..i] are now in sorted order   }

聯繫我們

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