(3)插入排序之一 直接插入排序

來源:互聯網
上載者:User

    直接插入排序(Straight
Insertion Sort)是一種最簡單的排序方法,它的基本操作是將一個記錄插入到已排好序的有序表中,從而得到一個新的、記錄數增1的有序表。時間複雜度為O(n^2)。理解:依次將每個待排序的記錄插入到一個有序序列的合適位置。插入的位置是和有序序列的每一個元素進行比較,然後確定的。

void CInsertionSort::StraightInsertion(void)
{
//元素0是哨兵。
const int count = 9;
int L[count] = {0, 49, 38, 65, 97, 76, 13, 27, 49};
//對順序表作直接插入排序。
for (int i = 2; i < count; i++)
{
if (L[i] < L[i - 1])
{
L[0] = L[i];
int j = i - 1;
do
{
L[j + 1] = L[j];
j--;
} while (L[0] < L[j]);
L[j + 1] = L[0];
}
}
//列印排序結果。
for (int i = 0; i < count; ++ i)
{
cout << L[i] << "\t";
}
cout << endl;
}

預設迴圈最初的有序序列只有一個元素。

聯繫我們

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