<pre name="code" class="cpp">/*
少量元素排序的有效方法
1、从第二个数据开始于前面的全部数据比较
2、将比较的数据插入到正确的位置
*/
#include<iostream>
using namespace std;
void insert_sort(int a[], int length);
int main()
{
int a[] = {2 ,5 ,8 ,3 ,9,10 ,4 ,6 ,1 ,7 };
int length = sizeof(a) / 4;
insert_sort(a, length);
for (int i = 0; i < length; i++)
{
cout << a[i] << " ";
}
cout << endl;
system("pause");
return 0;
}
void insert_sort(int a[] , int length)
{
for (int i = 1; i < length; i++)
{
for (int j = 0; j < i; j++)
{
if (a[i] < a[j])
{
//插入数据
//将数据放到正确位置,比该数据大的全部后移一位
int temp = a[i];
for (int m = i; m > j; m--)
{
a[m] = a[m - 1];
}
a[j] = temp;
break;
}
}
}
}
/*
外循环是需要比较的数据,内循环从数组的0位开始循环比较
*/
/*时间复杂度:最好O(n) 最坏O(n^2);空间复杂度O(n)*/
插入排序
最新推荐文章于 2024-12-13 15:13:27 发布