查找的元素
二、从键盘接收一个不超过20个数据元素的待排序表。1、输出待排序表。
2、对待排序表进行希尔排序,要求输出每趟排序的结果。
3、对原待排序表进行快速排序,要求输出每趟排序的结果。。
2011-05-19 16:18
程序代码:#include <stdio.h>
#define WAY
//#undef WAY
#define SIZE 20//表的最大长度
typedef int TYPE;//表中元素的类型
unsigned int length;//表的实际长度
TYPE table[SIZE];
//录取信息
void get_input(void)
{
while (scanf("%d", &table[length]))
{
length++;
}
}
//打印表
void print_table(void)
{
unsigned int index=0;
while (index != length)
{
printf("%d ", table[index]);
++index;
}
printf("\n");
}
#ifdef WAY
//调整
void adjust(unsigned int gap)
{
unsigned int index = 0;
unsigned int i = gap;
TYPE temp;
for(; index < length; index++)
{
temp = table[index];
for (i=index+gap; i < length; i++)
{
if (temp <= table[i])
{
temp += table[i];
table[i] = temp - table[i];
temp -= table[i];
}
i += gap;
}
table[index] = temp;
}
}
//希尔排序
void sort(unsigned int time)
{//升序排列
unsigned int gap = 2*(time-1)+1;
unsigned int counter = 0;
while (counter++ != time)
{
adjust(gap);
if (gap != 1)
{
gap = gap-2;
}
printf("第%d次排序结果: ", counter);
print_table();
}
}
#else
unsigned int adjust(unsigned int low, unsigned int high)
{//升序排列
TYPE temp = table[low];
while (low < high)
{
while (low < high && temp <= table[high])
{
--high;
}
table[low] = table[high];
while (low < high && temp >= table[low])
{
++low;
}
table[high] = table[low];
}
table[low] = temp;
return low;
}
//快速排序
void sort(unsigned int low, unsigned int high)
{
unsigned int i;
static unsigned int counter=1;
if (low < high)
{
i = adjust(low, high);
printf("第%d次排序结果: ", counter++);
print_table();
sort(low, i-1);
sort(i+1, high);
}
}
#endif
void function(void)
{
get_input();
print_table();
#ifdef WAY
printf("\t希尔排序\n");
sort(4);
#else
printf("\t快速排序\n");
sort(0, length-1);
#endif
print_table();
}
int main(void)
{
function();
return 0;
}
2011-05-19 21:50
2011-05-19 21:52
2011-05-25 23:25
2011-05-30 21:11