看别人写的觉得很简单,自己写可就有点不同,以后要多自己写!
void InsertSort(int a[],int n)
{
for(int i=1;i<n;i++)
{
int j=i-1;
while(j>=0 && a[i]<a[j])
{
j--;
}
//交换a[i] a[j+1]
if(j!=i-1)
{
int temp=a[i];
for(int k=i;k>j+1;k--)//j+1--i-1个元素后移,a[i]搬到a[j+1]
a[k]=a[k-1];
a[j+1]=temp;
}
}
}
void BinarySort(int a[],int n)
{
for(int i=1;i<n;i++)
{
int low=0,high=i-1;
while(low<=high)
{
int middle=(low+high)/2;
if(a[i]>=a[middle])
low=middle+1;
else
high=middle-1;
}//low的位置就是要插入的位置,why?Think!
//low+1-----i移动元素
int temp=a[i];
for(int k=i;k>low;k--)
{
a[k]=a[k-1];
}
a[low]=temp;
}
}