直接插入排序(高级版)之C++实现

直接插入排序(高级版)之C++实现

一、源代码:InsertSortHigh.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 一种查找比较操作和记录移动操作交替地进行的方法。
19 具体做法:
20  将待插入记录R[i]的关键字从右向左依次与有序区中记录R[j](j=i-1,i-2,…,1)的关键字进行比较:
21   ① 若R[j]的关键字大于R[i]的关键字,则将R[j]后移一个位置;
22   ②若R[j]的关键字小于或等于R[i]的关键字,则查找过程结束,j+1即为R[i]的插入位置。
23    关键字比R[i]的关键字大的记录均已后移,所以j+1的位置已经腾空,只要将R[i]直接插入此位置即可完成一趟直接插入排序。
24 
25  */
26 int insertSort(int array[], int n)
27 {
28     //定义变量,记录交换次数
29     int count = 0;
30     //定义中间变量,做为临时交换变量
31     int temp;
32     //遍历数组(进行排序)
33     cout << "开始对数组进行排序了..." << endl;
34     for (int i = 1; i < n; i++)
35     {
36         for (int j = i; j >= 1; j--)
37         {
38             cout << "" << (i + 1) << "趟第" << (j + 1) << "次排序" << endl;
39             if (array[j] < array[j - 1])
40             {
41                 temp = array[j];
42                 array[j] = array[j - 1];
43                 array[j - 1] = temp;
44                 cout << array[j] << "" << array[j + 1] << "互换了" << endl;
45                 //输出此时数组的顺序
46                 cout << "数组此时的顺序是:";
47                 print(array, 10);
48                 //每交换一次,记录数加1
49                 count++;
50             }
51             else
52             {
53                 break;
54             }
55         }
56     }
57     cout << "数组排序结束了..." << endl;
58     return count;
59 }
60 
61 int main()
62 {
63     //定义待排序的一维数组
64     int array[] = { 1, 3, 4, 5, 2, 6, 10, 9, 8, 7 };
65     //输出原始数组
66     cout << "原始数组是:" << endl;
67     print(array, 10);
68     //对数组进行排序
69     int count = insertSort(array, 10);
70     //输出排序后的数组
71     cout << "排序后的数组是:" << endl;
72     print(array, 10);
73     cout << "共交换" << count << "" << endl;
74     return 0;
75 }

 

二、运行效果

 

原文地址:https://www.cnblogs.com/zfc-java/p/7390735.html