插入排序:将数组的第一个数认为是有序数组,从后往前(从前往后)扫描该有序数组,把数组中其余n-1个数,根据数值的大小,插入到有序数组中,直至数组中的所有数有序排列为止。
时间复杂度是O(n^2)
代码如下:
#include<iostream>
using namespace std;
//交换数组元素位置位置
void swap(int& a, int& b)
{
int temp = a;
a = b;
b = temp;
}
void insertSort(int a[], int length)
{
for (int i = 1; i < length; i++)
{
for (int j = i - 1; j >= 0 && a[j + 1] < a[j]; j--)
{
swap(a[j], a[j + 1]);
}
}
}
int main()
{
int a[] = {5,7,2,66,55,33,96,35 };
int len = sizeof(a) / sizeof(a[0]);
insertSort(a, len);
for (int i = 0; i < len; i++)
{
cout << a[i] << " ";
}
cout << endl;
system("pause");
return 0;
}