- 思路分析
- 代码分析
- 时间复杂度分析
1.思路分析
2.代码分析
//直接插入排序
void InsertSort(int *a, int n)
{
//将下标为i的元素插入到已经拍好序的序列中
for (int i = 1; i < n;i++)
{
//end记录已经排好序的并且未与temp比较元素的下标,初始值为 0
int end = i - 1;
//temp记录本趟排序要插入的元素的值为a[end+1],此时end+1位置空余出来
int temp = a[end + 1];
while (end >= 0)
{
//找比temp小的元素
if (a[end] > temp)
{
//若a[end] > temp,将a[end]向后移到end+1位置处,此时end位置空余出来
a[end + 1] = a[end];
end--;
}
else//a[end] <= temp,说明找到了比temp小的元素,为a[end]
{
break;
}
}
//temp插入到a[end]的后面end+1位置处; 若end = -1,同样插入到end+1位置处
a[end + 1] = temp;
}
}
int main()
{
int a[] = {
5, 2, 4, 6, 1, 3 };
int size = sizeof(a) / sizeof(a[0]);
printf("排序前:");
PrintArray(a, size);//打印排序前
InsertSort(a, size);
printf("排序后:");
PrintArray(a, size);//打印排序后
system("pause");
return 0;
}
3.复杂度分析
通过分析插入排序的思想来分析时间复杂度。
对于每趟排序而言,最坏情况下,待插入元素与前面的每个元素都进行比较最后插入到第一个位置。时间复杂度为O(N)。
对于有 N 个元素的数组要进行 N-1 趟排序,每次都是O(N),那么总的时间复杂的就是O(N*N)。