1.前言
工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。
2.实现步骤
将第一待排序序列第一个元素看做一个有序序列,把第二个元素到最后一个元素看成是未排序序列。
从头到尾依次遍历未排序序列,将遍历到的每个元素插入有序序列的适当位置。(如果待插入的元素与有序序列中的某个元素相等,则将待插入元素插入到相等元素的后面。)
C语言
代码:
#include <stdio.h>
void InsertionSort(int* a, int sz) //插入排序
{
int i, j, temp;
for (i = 1; i < sz; i++) //从第二个元素开始
{
temp = a[i]; //记录待排的元素
j = i - 1;
while (j >= 0 && (a[j] > temp)) //当并未越界,且前面的较大时,元素向后移动,便于插入
{
a[j + 1] = a[j];
j--;
}
a[j + 1] = temp; //插入元素
}
}
int main()
{
int a[] = { 1,8,6,4,3,10,4 };
int sz = sizeof(a) / sizeof(a[0]);
int i;
InsertionSort(a, sz);
for (i = 0; i < sz; i++)
printf("%d ", a[i]);
return 0;
}
C++
#include <iostream>
using namespace std;
void InsertionSort(int* Array, int sz) //插入排序
{
for (int i = 1; i < sz; i++)
{
int temp = Array[i];
int j = i - 1;
while (j >= 0 && Array[j] > temp) //未越界,并且寻找合适的位置插入
{
Array[j + 1] = Array[j];
j--;
}
Array[j+1] = temp; //在比Array[j]大的后面位置(即Array[j+1])插入temp(Array[i])
}
}
int main()
{
int array[7] = { 1,5,9,5,6,4,2 };
int len = sizeof(array) / sizeof(array[0]);
InsertionSort(array, len); //调用插入排序
for (int i = 0; i < len; i++)
printf("%d ", array[i]);
return 0;
}
C++ 2.0
#include <iostream>
using namespace std;
#include <algorithm>
void InsertSort(int a[], int n)
{
for (int i = 0; i < n; i++)
{
for (int j = i; j > 0 && a[j] < a[j - 1]; j--)
{
swap(a[j], a[j - 1]);
}
}
}
int main()
{
int n;
cin >> n;
int* a = new int[n];
for (int i = 0; i < n; i++)
cin >> a[i];
InsertSort(a, n);
for (int i = 0; i < n; i++)
cout << a[i] << " ";
delete[]a;
return 0;
}
优化:拆半插入
思路:
依据插入排序的思路,可以再设置两个索引,先根据中间索引找到合适的插入位置,再插入元素
代码:
#include <stdio.h>
void BinarySort(int* a, int sz)
{
int i, j, LeftIndex, RightIndex,MidIndex,temp;
for (i = 1; i < sz; i++)
{
temp = a[i];
LeftIndex = 0;
RightIndex = i - 1;
while (LeftIndex <= RightIndex) //循环的条件
{
MidIndex = (LeftIndex + RightIndex) / 2;
if (temp > a[MidIndex]) //当要插入的元素比中间索引大的时候,更新左索引
LeftIndex = MidIndex + 1;
else
RightIndex = MidIndex - 1;
}
for (j = i - 1; j >= LeftIndex; j--) //从左索引到i-1依次移动,便于元素的插入
{
a[j + 1] = a[j];
}
a[LeftIndex] = temp; //元素插入找到的位置,即左索引的位置
}
}
int main()
{
int a[] = { 1,8,6,4,3,10,4 };
int sz = sizeof(a) / sizeof(a[0]);
int i;
BinarySort(a, sz);
for (i = 0; i < sz; i++)
printf("%d ", a[i]);
return 0;
}
C++版本 二分查找插入排序
#include <iostream>
using namespace std;
void BinaryInsertSort(int a[], int n)
{
for (int i = 1; i < n; i++)
{
int temp = a[i]; //待插入的数据
int L = 0;
int R = i - 1;
while (L <= R)
{
int mid = ((L + R) >> 1);
if (temp > a[mid])
L = mid + 1;
else
R = mid - 1;
}
int j;
for (j=i-1;j >= L; j--) //统一向后移动
{
a[j + 1] = a[j];
}
//j出来会变成L-1
a[L] = temp;
}
}
int main()
{
int n;
cin >> n;
int* a = new int[n];
for (int i = 0; i < n; i++)
cin >> a[i];
BinaryInsertSort(a, n);
for (int i = 0; i < n; i++)
cout << a[i] << " ";
delete[]a;
return 0;
}
3.总结
插入排序的思路是,假定要插入的index之前都有序,再找到合适的位置,插入index即可
时间复杂度为0(N2)
插入排序较为简便,将未排序元素插入已排序的元素序列中。
4.更新日志
2022.3.7 整理(C)
2022.3.17 更新C++
欢迎指正,讨论,交流~~