//
// main.cpp
// Sorting
//
// Created by yanzhengqing on 12-12-6.
// Copyright (c) 2012年 yanzhengqing. All rights reserved.
#include <iostream>
using namespace std;
int input_array(intconst *p)
{
printf("please input the array numbers......\n");
for (uint i =0; i <10;i++)
{
scanf("%d",p++);
}
return0;
}
int output_array(intconst *p)
{
for (uint i =0; i <10;i++)
{
printf("%d\t",*(p++) );
}
return0;
}
///希尔排序 Diminishing increment sort也属于插入排序的一种
/*
基本思想是先将整个待排记录序列分割成为若干子序列分别进行直接插入排序,待整个序列中的记录基本有序的时候,在对全体进行一次直接插入排序
同时注意应使增量序列中没有除1以外的公因子,并且最后一个增量值必须等于1
实例数据
//21 32 43 22 56 87 65 49 76 10
//a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
//a[0] a[3] a[6] a[9]
//21 32 43 22 10 87 65 49 76 56
*/
int shell_sort(int *a,int n)
{
int k =5;//初始化增量,我这里取的5然后是3最后是1.具体增值设为多少为好这还是个数学难题(严蔚敏数据结构上介绍,大家可以探索探索)
int raid =0, num =1;
int temp =0, j =0;
printf("Shell's sort\n");
while (k>0)
{
while(raid<k) //一共分为k个批次,k个批次排序结束为一趟
{
for(int i = k+raid; i < n; i+=k)
{
temp = a[i];
for (j = i; j-k >=0 && temp < a[j - k]; j-=k) //精髓是从后向前比较,注意这里 j-k>=0 一开始写算法时候没有发现这里的界限问题,very important!
{
a[j] = a[j - k];
}
a[j] = temp;
}
raid++;
}
cout<<"k="<<k<<endl;
cout<<"这是第~~"<<num<<"~~趟排序结果"<<endl;
output_array(a);
cout<<endl;
raid =0;
num ++;
k -=2;
}
return0;
}
int main(int argc,constchar * argv[])
{
int array[10] = {0};
input_array(array);
shell_sort(array,sizeof(array)/sizeof(int));
return0;
}
***************************************************************************************************
执行效果:
please input the array numbers......
21
32
43
22
56
87
65
49
76
10
Shell's sort
这是第~~1~~趟排序结果
21324322 10 87654976 56
这是第~~2~~趟排序结果
21104322 32 76564987 65
这是第~~3~~趟排序结果
10212232 43 49566576 87
这个希尔排序可能不是最优的写法,望大家多多指点,我再稍作改动。争取达到最优的写法!
有什么想法记得给我留言!