《演算法導論》CLRS演算法C++實現(一)P11 插入排序

來源:互聯網
上載者:User

過幾個月要面試了,最近在看《演算法導論》,想把裡面的演算法都用C++實現一遍。今天是第一個演算法,比較簡單。

第二章 演算法入門

插入排序

虛擬碼實現

INSERTION-SORT(A)  《演算法導論》P10

1 for j ← 2 to length[A]2     do key ← A[j]3         //Insert A[j] into the sorted sequence A[1 ‥ j - 1].4         i ← j - 15         while i > 0 and A[i] > key6             do A[i + 1] ← A[i]7                 i ← i - 18         A[i + 1] ← key

C++代碼實現

 1 #include <iostream> 2  3 using namespace std; 4  5 void insertSort(int *arr, int n) 6 { 7     int i, j, key; 8     for(j = 1; j < n; j++) 9     {10         key = arr[j];11         i = j - 1;12         while((i >= 0) && (arr[i] > key))13         {14             arr[i + 1] = arr[i];15             i--;16         }17         arr[i + 1] = key;18     }19 }20 21 int main()22 {23     int a[] = {2, 4, 32, 64, 67, 34, 78, 23, 3456, 2345, 123, 1, 3};24     insertSort(a, 13);25     for(int i = 0; i < 13; i++)26     {27         cout << a[i] << " ";28     }29     cout << endl;30     return 0;31 }

希望能一直堅持下去吧。

相關文章

聯繫我們

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