冒泡排序算法
#include #define MAXSIZE 100 /*文件中记录个数的最大值*/ typedef int keytype; /*定义排序码类型为整数类型*/ typedef struct{ keytype key; int other; /*此处还可以定义记录中除排序码外的其它域*/ }recordtype; /*记录类型的定义*/ typedef struct{ recordtype r[MAXSIZE+1]; int length; /*待排序文件中记录的个数*/ }table; /*待排序文件类型*/ /*****************************************/ /* 函数功能:建立待排序的初始数据 */ /* 函数参数:指针变量t */ /* 函数返回值:空 */ /* 文件名:init.c 函数名:init() */ /*****************************************/ void init(table *t) { int x,i; t->length=0;/*初始化*/ printf(\"请输入待排序数据的排序码(-999结束):\\n\"); scanf(\"%d\从键盘输入数据*/ while(x!=-999) /*假设输入数据为-999则输入结束*/ { t->length++; t->r[t->length].key=x; scanf(\"%d\ } } /*除通过键盘接受数据外,也可以通过从数据文件中等方式接受数据*/ /*这里仅对待排序记录的排序码进行了输入,记录的其他数据没有输入*/ /*这里假设接受的数据总数不会超过MAXSIZE个,所以没有进行判断是否溢出*/ /*****************************************/ /* 函数功能:输出数据 */ /* 函数参数:结构变量t */ /* 函数返回值:空 */ /* 文件名:display.c 函数名:display() */ /*****************************************/ void display(table t) { int i; for(i=1;i<=t.length;i++) printf(\"%5d\ } void bubblesort(table *tab) { int i,j,done; i=1;done=1; while(i<=tab->length&&done) { done=0; for(j=1;j<=tab->length-i;j++) if(tab->r[j+1].key { tab->r[0]=tab->r[j]; tab->r[j]=tab->r[j+1]; tab->r[j+1]=tab->r[0]; done=1; } i++; } } void main() {table t; init(&t); bubblesort(&t); display(t); printf(\"\\n\"); } 因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- igbc.cn 版权所有 湘ICP备2023023988号-5
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务