基本思想:
把一个个元素插入到有序序列中。
排序过程:整个排序过程为n - 1趟插入,即先将序列中的第一个记录看成是一个有序子序列,然后从第2个记录开始,逐个进行插入,直至整个序列有序。
实质:对线性表执行n - 1次插入操作,只是先要找到插入位置。
V[0], V[1], …, V[i-1]已经排好序。这时,用V[i]的关键字与V[i-1], V[i-2], …的关键字进行比较, 找到插入位置即将V[i]]插入, 原来位置上的对象向后顺移。
插入排序关键点:1、拿出一个元素,留出位置、2 符合条件的元素后移。
时间复杂度O(n^2)
示例代码:
#include <iostream>
#include <cstdio>
#include <ctime>
#include <iomanip>
using namespace std;
int arr[10000];
void insertSrot(int *a, int len)
{
for (int i = 1; i < len; i++) {
int k = i; // 待插入位置
int tmp = arr[k];
for (int j = i - 1; j >= 0 && arr[j] > tmp; j--) {
arr[j + 1] = arr[j]; // 元素后移
k = j;
}
arr[k] = tmp; // 元素插入
}
}
void printArray(int *a, int len)
{
for (int i = 0; i < len; i++) {
if (i != 0 && i % 10 == 0) {
cout << endl;
}
cout << setw(3) << a[i] << ' ';
}
cout << endl;
}
int main()
{
srand(time(0));
cout << "Please input length of array: ";
int len;
cin >> len;
for (int i = 0; i < len; i++) {
arr[i] = rand() % 100;
}
cout << "Before sorting:\n";
printArray(arr, len);
insertSrot(arr, len);
cout << "After sorting:\n";
printArray(arr, len);
return 0;
}
/*
Please input length of array: 20
Before sorting:
41 5 45 17 35 58 29 61 98 89
27 8 97 83 89 3 25 59 12 44
After sorting:
3 5 8 12 17 25 27 29 35 41
44 45 58 59 61 83 89 89 97 98
*/
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/zyq522376829/article/details/46755155