#include
#include
using namespace std;
==================================================================================================================
一、插入类排序
1.直接插入排序,时间复杂度o(n^ 2),比较次数最大值约为n ^ 2/2,移动次数最大值约为n^2/2
/*
1.设待排序的记录存放在数组中,r[1]是一个有序序列
2.循环(n-1)次,每次,查找r[i]在已排好序的序列中的位置,直接插入,最后得到表长为n的序列
/
/
具体实现时,有2种方法,顺序比较(r[i]与r[1]…r[i-1]从前往后顺序比较),逆序比较(r[i]与r[i-1]…r[1]比较),为了查找插入位置避免溢出,在r[0]设置哨兵
*/
void show(int a[], int length) {
for (int i = 1; i <= length; i++) {
cout << a[i] << " ";
}
cout << endl;
}
void InsertSort(int a[], int length) {//从小到大排序
int i = 0,j=0;
int compareTime = 0,changeTime=0;
for (i = 2; i <= length; i++) {//从小到大
if (a[i] < a[i - 1]) {
a[0] = a[i];//哨兵作用1:保存数值
changeTime++;
a[i] = a[i - 1];
changeTime++;
for (j = i - 2; a[0] < a[j]; compareTime++,--j) {//哨兵作用1:防止溢出,记录从后向前寻找插入位置
a[j + 1] = a[j];
changeTime++;
}
a[j + 1] = a[0];//还原,找到 插入位置
changeTime++;
}
compareTime++;
printf("The %2d time sort:\t", (i - 1));
show(a, length);
}
cout << "Key word ComareTime=" << compareTime << endl;
cout << "Key word ChangeTime=" << changeTime << endl;
}
算法分析
/*
时间复杂度:
最好情况(正序:非递减有序排列,比较1次),最坏情况:非递增有序排列,比较次数和记录移动次数为n^2/4
空间复杂度:O(1)
特点:(1)稳定排序
(2)简便,容易实现
(3)也适合链式存储
(4)更适合基本有序的序列
*/
int main() {
int *a = new int[17];
int length = 16;
srand(unsigned(time(NULL)));
for (int i = 1; i <= 16; i++) {
a[i]=rand()% 90 + 10;
}
cout << “============= =” << endl;
cout << “直接插入排序:” << endl;
cout << “==============” << endl;
cout << “before sort:” << ends;
for (int i = 1; i <= 16; i++) {
cout<<a[i]<<" ";
}
cout << endl;
InsertSort(a, length);
cout << “after sort:” << ends;
for (int i = 1; i <= 16; i++) {
cout << a[i] << " ";
}
cout << endl;
delete a;
a = NULL;
}