插入排序:
对于数据空间减小的数据,采用直接插入排序。直接上代码。(编程环境 kali+sublime+gcc , 程序使用指针和数组两种方式(差别不大),和i和j之间微小的关系)
时间复杂度O(n^2),空间复杂度O(1)。
#include <iostream>
#include <stdlib.h>
using namespace std;
void insertsort(int *a,int n)
{
int temp;
for(int i=1;i<n;i++)
{
temp=*(a+i);
int j=i-1;
while(j>=0&&*(a+j)>temp)
{
*(a+j+1)=*(a+j);
j--;
}
*(a+j+1)=temp;
}
}
void insertsort2(int *a,int n)
{
int temp;
for(int i=1;i<n;i++)
{
temp=a[i];
int j=i;
while(j>0&&a[j-1]>temp)
{
a[j]=a[j-1];
j--;
}
a[j]=temp;
}
}
int insertloc(int *a,int low,int high,int value)
{
if(low==high)
{
if(value>*(a+low))
return (low+1);
else
return low;
}
int mid = (low + high)/2;
if(value>*(a+mid)&&value>*(a+mid+1))
insertloc(a,mid+1,high,value);
else if(value<*(a+mid)&&value<*(a+mid+1))
insertloc(a,low,mid,value);
else
return (mid+1);
}
void insertsortf(int *a,int n)
{
int temp;
int loc;
for(int i=1;i<n;++i)
{
temp = *(a+i);
int j=i-1;
loc = insertloc(a,0,j,temp);
cout<<"insert_location"<<loc<<endl;
while(j>=loc)
{
*(a+j+1)=*(a+j);
j--;
}
*(a+loc)=temp;
for(int m = 0;m <= i;++m)
cout<<*(a + m)<<" ";
cout<<endl;
}
}
int main(int argc,char *argv[])
{
int *arr;
int num;
cout<<"please input the sum of arr"<<endl;
cin>>num;
arr = (int *)malloc(num*sizeof(int));
cout<<"please input the array!\n";
for(int i=0;i<num;i++)
{
cin>>*(arr+i);
}
cout<<"\n";
for(int j=0;j<num;j++)
{
cout<<*(arr+j)<<"\t";
}
cout<<"\n";
//insertsort(arr,num);
//insertsort2(arr,num);
insertsortf(arr,num);
for(int j=0;j<num;j++)
{
cout<<*(arr+j)<<"\t";
}
cout<<"\n";
free(arr);
return 0;
}