標籤:font cpp -- int 元素 代碼 分享 空間 數組排序
直接插入排序(初級版)之C++實現
一、原始碼:InsertSortLow.cpp
1 /*直接插入排序思想: 2 假設待排序的記錄存放在數組R[1..n]中。初始時,R[1]自成1個有序區,無序區為R[2..n]。 3 從i=2起直至i=n為止,依次將R[i]插入當前的有序區R[1..i-1]中,產生含n個記錄的有序區。 4 */ 5 6 #include<iostream> 7 using namespace std; 8 /*定義輸出一維數組的函數*/ 9 void print(int array[], int n)10 {11 for (int i = 0; i < n; i++)12 {13 cout << array[i] << " ";14 }15 cout << endl;16 }17 /*18 首先在當前有序區R[1..i-1]中尋找R[i]的正確插入位置k(1≤k≤i-1);19 然後將R[k..i-1]中的記錄均後移一個位置,騰出k位置上的空間插入R[i]。20 注意:21 若R[i]的關鍵字大於等於R[1..i-1]中所有記錄的關鍵字,則R[i]就是插入原位置。22 */23 int insertSort(int array[], int n)24 {25 //定義變數,記錄交換次數26 int count = 0;27 //定義中間變數,做為臨時交換變數28 int temp;29 int j;30 //遍曆數組(進行排序)31 cout << "開始對數組進行排序了..." << endl;32 for (int i = 1; i < n; i++)33 {34 //當左邊元素大於右邊元素時35 if (array[i] < array[i - 1])36 {37 //將當前的數組元素儲存到臨時變數中38 temp = array[i];39 //將從i位置(比temp大的元素)開始的數組元素整體後移40 for (j = i - 1; j >= 0 && array[j]>temp; j--)41 {42 cout << "第" << (i + 1) << "趟第" << (j + 1) << "次排序" << endl;43 //將數組中的元素整體後移一個單位44 array[j + 1] = array[j];45 cout << array[j] << "和" << array[j + 1] << "互換了" << endl;46 //輸出此時數組的順序47 cout << "數組此時的順序是:";48 print(array, 10);49 //每交換一次,記錄數加150 count++;51 }52 array[j + 1] = temp;53 }54 }55 cout << "數組排序結束了..." << endl;56 return count;57 }58 59 int main()60 {61 //定義待排序的一維數組62 int array[] = { 1, 3, 4, 5, 2, 6, 10, 9, 8, 7 };63 //輸出原始數組64 cout << "原始數組是:" << endl;65 print(array, 10);66 //對數組進行排序67 int count = insertSort(array, 10);68 //輸出排序後的數組69 cout << "排序後的數組是:" << endl;70 print(array, 10);71 cout << "共交換" << count << "次" << endl;72 return 0;73 }
二、運行效果
直接插入排序(初級版)之C++實現