1.排序
1.1 插入排序
时间复杂度:O(n)~O(n*n)
空间复杂度:O(1)
稳定
步骤:
1.设第一个元素为有序列。
2.取有序列后面的一个元素。
3.将该元素插入到有序列中的正确位置。
4.依次重复3、4步,直到完成排序。
#include<iostream>
usingnamespacestd;
//插入升序
voidinsert_sort_asc(int*arr, intn)
{
for (inti=0; i<n-1; i++)
{
intend=i;//有序列的最后一个元素
inttemp=arr[end+1];//当前需要插入排序的元素
while (end>=0)//最坏情况下,遍历至有序列的第一个元素
{
if (temp<arr[end]) //待插入的数小,就将大数往后移
{
arr[end+1] =arr[end];//后移
end--;//向前继续找位置
}
else
{
break;//temp更大,则找到要插入的位置,退出循环
}
}
arr[end+1] =temp;//temp插在较小数后
}
}
//插入降序
voidinsert_sort_dec(int*arr, intn)
{
for (inti=0; i<n-1; i++)
{
intend=i;
inttemp=arr[end+1];
while (end>=0)
{
if (temp>arr[end])
{
arr[end+1] =arr[end];
end--;
}
else
{
break;
}
}
arr[end+1] =temp;
}
}
voidoutput(int*arr, intn)
{
for (inti=0; i<n; i++)
{
cout<<arr[i] <<" ";
}
cout<<endl;
}
intmain()
{
intn, arr[99],copy[99];
cout<<"Number of inputs:";
cin>>n;
cout<<"Inputs array:";
for (inti=0; i<n; i++)
{
cin>>arr[i];
}
memcpy(copy, arr, n*sizeof(int));
insert_sort_asc(copy, n);
output(copy, n);
insert_sort_dec(arr, n);
output(arr, n);
}