转载请注明出处。
假设升序排列n个元素。
1、将序列分为有序区和无序区,排序前,有序区元素个数为1,无序区个数为n-1。
2、将无序区的第一个元素插入到有序区,插入位置通过比较确定,直接插入排序是稳定的排序算法。
3、插入过程中需要向右移动插入位置后的元素。
时间复杂度:
最坏情况下,比较次数为n(n-1)/2,时间复杂度为O()。
测试代码:
#include<iostream>
#include<iterator>
using namespace std;
void insertionSort(int list[], int length){
int temp, index;
for(int firstOutOfOrder=1; firstOutOfOrder < length; firstOutOfOrder++)
if(list[firstOutOfOrder] < list[firstOutOfOrder-1])
{
temp = list[firstOutOfOrder];
list[firstOutOfOrder] = list[firstOutOfOrder-1];
index = firstOutOfOrder-1;
while(index > 0 && list[index-1] > temp)//find insertion location
{
list[index] = list[index-1];
index--;
count++;
}
list[index] = temp;
}
}
int main(){
ostream_iterator<int> screen(cout, ", ");
int list[] = {9, 8, 7, 6, 5, 4};
insertionSort(list, sizeof(list)/sizeof(int));
copy(list, list+sizeof(list)/sizeof(int), screen);
cout << endl;
}
参考资料:
本文详细介绍了插入排序算法的基本原理,包括其工作流程、时间复杂度分析及C++实现代码。通过实例展示如何将无序元素逐步插入到已排序部分中,确保整体序列最终达到完全有序状态。
864

被折叠的 条评论
为什么被折叠?



