插入排序
特点:原址排序,比较排序,(最坏的情况)时间复杂度O(n^2)
#include <iostream>
void insertion_sort(int *arr,int start,int end)
{
for (int i = start+1; i < end+1; ++i) {
int key = arr[i];
int j = i-1;
while (j>=start && key<arr[j])
{
arr[j+1] = arr[j];
j--;
}
arr[j+1] = key;
}
}
void show(int *arr,int length)
{
for(int i=0;i<length;i++)
{
std::cout<<arr[i]<<" ";
}
std::cout<<std::endl;
}
int main()
{
int arr[] = {1,4,6,9,2,5,10,3,7};
show(arr,sizeof(arr)/sizeof (int));
insertion_sort(arr,0,sizeof(arr)/sizeof (int)-1);
show(arr,sizeof(arr)/sizeof (int));
return 0;
}
嵌入递归的插入排序
T(n) = T(n) + n-1
(最坏的情况)时间复杂度O(n^2)
void recursion_insertion_sort(int *arr,int start,int end)
{
if(start<end)
{
recursion_insertion_sort(arr,start,end-1);
int pos = end - 1;
int key = arr[end];
while (pos >= start && key < arr[pos])
{
arr[pos+1] = arr[pos];
pos--;
}
arr[pos+1] = key;
}
}