#include <iostream>
using namespace std;
void direct_sort(int a[], int len)
{
int i, j;
for(i=2; i<=len; i++)
{
a[0] = a[i];
j = i-1;
while(a[0] < a[j])
{
//找到要插入的位置j+1
a[j+1] = a[j];
j--;
}
a[j+1] = a[0];
}
cout<<"直接插入排序:";
for(i=1; i<len; i++)
cout<<a[i]<<" ";
cout<<endl;
}
void half_insert_sort(int a[], int len)
{
int i, j, low, high, mid;
for(i=2; i<=len; i++)
{
a[0] = a[i];
low = 1;
high = i - 1;
while(low <= high)
{
//找到要插入的位置high+1
mid = (low+high)/2;
if(a[0] > a[mid])
low = mid + 1;
else
high = mid - 1;
}
for(j=i-1; j>=high+1; j--)
a[j+1] = a[j];
a[high+1] = a[0];
}
cout<<"折半插入排序:";
for(i=1; i<len; i++)
cout<<a[i]<<" ";
cout<<endl;
}
void shell_sort(int a[], int len)
{
int d = len/2;
int i, j, temp;
while(d > 0)
{
for(i=d; i<len; i++)
{
j = i - d;
while(j >= 0)
{
if(a[j] > a[j+d])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
j = j - d;
}
else
j = -1;
}
}
d = d/2;
}
cout<<"希尔排序:";
for(i=0; i<len; i++)
cout<<a[i]<<" ";
cout<<endl;
}
int main(void)
{
int a[] = {9, 4, 6, 1, 8, 3, 2};
int len = sizeof(a)/sizeof(int);
//直接排序,a[0]可以直接忽略
// direct_sort(a, len);
//折半插入排序,a[0]可以直接忽略
// half_insert_sort(a, len);
//希尔排序
shell_sort(a, len);
return 0;
}
数据结构几种插入排序
最新推荐文章于 2024-04-22 07:55:00 发布