个人学习整理:C++版插入排序

来源:互联网 发布:人工智能 蒋里博士 编辑:程序博客网 时间:2024/04/25 01:15
/************************插入排序***********************//*插入排序平均时间复杂度为O(n^2),适用于排序小的列表*//*若列表基本有序,则插入排序比冒泡、选择更有效率。 */#include<iostream> using namespace std; void InsertSort(int* pData,int Count) {  for(int i=1;i<Count;i++)//循环从第二个数组元素开始,因为arr[0]作为最初已排序部分 {     int temp=pData[i];//temp标记为未排序第一个元素     int j=i-1; while (j>=0 && pData[j]>temp)/*将temp与已排序元素从小到大比较,寻找temp应插入的位置*/ {     pData[j+1]=pData[j];     j--; } pData[j+1]=temp; } } void main() {  int data[] = {10,9,8,7,6,5,4}; int length=sizeof(data)/sizeof(int);for (int i=0;i<length;i++)cout<<data[i]<<" ";cout<<endl;InsertSort(data,length); for (i=0;i<length;i++) cout<<data[i]<<" ";}

0 0
原创粉丝点击