从这一篇开始,计划复习一下数据结构的基本知识。一来是为了开年之后的找工作,二来是为了想提升自己的编程能力。由于这些数据结构知识点,之前都学习过,这里我们就提炼出每个知识点的核心,以及代码实现。
这篇先说排序算法中的插入排序。
平均时间复杂度:O(n^2)。
代码实现如下:
#include<iostream>
using namespace std;
void InsertSort(int a[], int n)
{
for(int i = 1; i < n; i++)
{
if(a[i] < a[i-1]) // a[i]是待排元素,前面i-1个数已经排序好
{
int j = i-1; // 准备前移
int x = a[i];
a[i] = a[i-1];
while(x < a[j])
{
a[j+1] = a[j];
j--;
}
a[j+1] = x;
}
}
}
int main()
{
int a[] = {2, 1, 5, 8, 4, 3};
InsertSort(a, 6);
for(int i = 0; i< 6; i++)
cout<<a[i]<<' ';
cout<<endl;
return 0;
}原文地址:http://blog.csdn.net/puqutogether/article/details/43890453