十大经典排序算法之插入排序【三】
【插入排序】(Insert Sort)
a) 原理
插入排序通过对未排序数组中从后向前扫描,找到对应未知并插入,完成排序。
b) 演示动态图

c) 算法步骤
l 查找数组元素,假设第一个已经被排序;
l 取下一个元素,依次从后向前比较,如果比所取元素大,则向后移一位,直到找到比所取元素小的元素;
l 将所取元素插入到该位置,则该位置之前所有元素均为已排序序列;
l 以此类推。
d) 代码实现
1 #include <iostream> 2 using namespace std; 3 void SelectSort(int [],int); 4 void PrintStr(int [],int); 5 void InsertSort(int [],int); 6 7 int main() 8 { 9 int str[] = {2,5,6,1,53,26,64,18,98,18}; 10 int strlen = sizeof(str)/sizeof(str[0]); 11 cout << "排序前数组序列:"; 12 PrintStr(str,strlen); 13 InsertSort(str,strlen); 14 cout << "排序后数组序列:"; 15 PrintStr(str,strlen); 16 return 0; 17 } 18 //函数实现之插入排序:依次将最小数值向前移; 19 void InsertSort(int str[],int strlen) 20 { 21 int PreIndex,Current; 22 for (int i = 1;i < strlen;i++) 23 { 24 PreIndex = i - 1; 25 Current = str[i];//将最小值保存下来 26 while (PreIndex >=0 && Current < str[PreIndex]) 27 { 28 str[PreIndex+1] = str[PreIndex]; 29 PreIndex--; 30 } 31 str[PreIndex+1] = Current;//将最小值前移 32 } 33 } 34 void PrintStr(int str[],int strlen) 35 { 36 for (int i = 0;i < strlen;i++) 37 cout << str[i] << ','; 38 cout << endl; 39 }
参考博客:https://www.cnblogs.com/onepixel/articles/7674659.html,再次感谢!

浙公网安备 33010602011771号