交换排序
2015-09-12 00:08
316 查看
交换排序中的冒泡排序,快速排序
#include<stdio.h> #include<stdlib.h> #define N 10 typedef int KeyType; //定义关键字类型 typedef int DataType; //其他数据类型 typedef struct //记录数据结构 { KeyType key; //关键字 DataType data; //其他数据 }RecType; /* InitRec : 创建排序的结构体数组 */ void InitRec(RecType arr_Rec[], KeyType a[], int n) { int i = 0; for (i = 0; i < n; ++i) { arr_Rec[i].key = a[i]; //排序的数据 arr_Rec[i].data = 0; } } /* ShowData: 递归方式顺序打印排序结构体数组的关键字 */ void ShowData(RecType arr_Rec[], int n) { if (n == 0) //到达末尾 { printf("\n\n"); return; } else { printf(" %-5d", arr_Rec[0].key); RecType *p; p = arr_Rec; p++; ShowData(p, n - 1); } } /* BubbleSort: 冒泡排序,将最小的数往上冒*/ void BubbleSort(RecType R[], int n) { int i = 0; int j = 0; RecType temp; for (i = 0; i < n-1; i++) { for (j = n - 1; j>i; j--) //在i循环中,有序区元素增加,j循环依次减少,无序区的元素减少 { if (R[j - 1].key > R[j].key) { temp = R[j - 1]; R[j - 1] = R[j]; R[j] = temp; } } } } /* QuickSort: 快速排序算法 */ void QuickSort(RecType R[], int s,int t) { int i = s; int j = t; RecType temp; if (s < t) //区间内至少存在2个元素的情况 { temp = R[s]; //用区间第一个元素作为基准 while (i != j) { while (j>i && R[j].key >= temp.key) //从后开始往前与基准值对比 j--; R[i] = R[j]; while (i < j && R[i].key <= temp.key) //从前开始往后与基准值对比 i++; R[j] = R[i]; } R[i] = temp; QuickSort(R, s, i - 1); QuickSort(R, i + 1, t); } } int main() { int a = { 4, 2, 6, 9, 5, 7, 1, 3, 8, 10 }; //int a = {10,9,8,7,6,5,4,3,2,1}; //int a = {1,2,3,4,5,6,7,8,9,10 }; RecType arr_Rec ; InitRec(arr_Rec, a, N); ShowData(arr_Rec, N); //BubbleSort(arr_Rec, N); QuickSort(arr_Rec, 0, N-1); ShowData(arr_Rec,N); system("pause"); return 0; }
相关文章推荐
- HDU 4407 Sum(容斥)
- Tomcat安装、配置、优化及负载均衡详解
- EditText的drawableleft跟随其Gravity
- 活用maven使web.xml可以用maven变量
- 行列式的理解
- POJ 2773 Happy 2006(二分+容斥)
- Hadoop-eclipse-plugin插件安装
- 《机器学习实战》学习笔记:基于朴素贝叶斯的分类方法
- Yii2框架中一些折磨人的坑
- PHP比C/C++或Java少了什么?多线程,多线程,多线程……
- 为什么是“程序猿”而不是“程序媛”?
- Sublime Text3技巧使用
- Node.js
- Sublime Text
- P2P网贷理财入门知识
- 不必放大融金所事件对P2P行业影响
- 投资理财五字秘诀
- JAVA String类与常量池,堆之间的错综复杂...
- 关于引入第三方jar包引发的java.lang.NoClassDefFoundError解决
- Python读取中文txt乱码问题