超简单的shell排序
数据结构实验课内容,加上二分法查找:
1.读入或用随机函数生成10个整数作为数组元素;
2.调用排序函数进行排序,输出升序的排序结果;
3.修改排序函数,变成降序排序,调用之后输出排序结果;
4.读入一个数组元素,调用折半查找函数,输出该元素在数组中的位置;
5.读入一个非数组元素,调用折半函数,输出“找不到” ;
6.改进折半查找函数,使之能统计元素之间的比较次数并输出。
#include "stdio.h"
#include "time.h"
void shell_insert(char *L,int dk,int type) {
int i,j;
for(i=dk+1;i<=10;i++) {
if( (type ? L[i]
L[0]=L[i];
for(j=i-dk;j>0&&(type?L[0]
L[j+dk]=L[j];
L[j+dk]=L[0];
}
}
}
void shell_sort(char *L,int type) {
int i,j,dlta[3]={3,2,1};
for(i=0;i<3;i++) {
shell_insert(L,dlta[i],type);
/* printf("the %d time sorted_group is ",i);
for(j=0;j<11;j++)
printf("%c ",L[j]);
printf("\n");
*/ }
}
int bin_search(char *L,char key,int *count) {
int low,high,mid;
low=1;high=10;
*count=1;
while(low <= high) {
mid=(low+high)/2;
if(L[mid]==key) return mid;
else if(L[mid]>key) low = mid+1;
else high = mid -1;
(*count)++;
}
return 0;
}
int main(void)
{
int i,find_count;
char key,group[11];
srand((unsigned)time(NULL));
printf("the group is ");
for(i=1;i<11;i++)
printf("%c ",group[i]=rand()%26+'A');
printf("\n");
shell_sort(group,1);
printf("the up sorted_group is ");
for(i=1;i<11;i++)
printf("%c ",group[i]);
printf("\n");
shell_sort(group,0);
printf("the down sorted_group is ");
for(i=1;i<11;i++)
printf("%c ",group[i]);
printf("\n");
printf("enter the key you want\n");
scanf("%c",&key);
while(1){
if(i=bin_search(group,key,&find_count))
printf("position is %d,find_count is %d\n",i,find_count);
else
printf("not found\n");
printf("continue? n for exit\n");
scanf(" %c",&key);
if(key=='n')break;
}
}
