排序算法_2,快速排序
来源:互联网 发布:设计软件培训学校 编辑:程序博客网 时间:2024/05/21 11:08
#include <stdio.h>#include <malloc.h>//快速排序 平均时间复杂度O(NlogN) 最差时间复杂度为O(N^2)//从小到大排序void quickSort(int *a, int len){ int temp; //数组头尾的两个下标 int head=0, tail=len-1; if (head > tail) return; //随机取的一个数,不过为了避免越界,a[0]最保障 int flagNum = a[0]; while (head < tail){ //从尾到头比较,直到有数小于flagNum,或者头尾重叠 while (a[tail] >= flagNum && tail>head){ tail--; } //从头到尾比较,直到有数大于flagNum,或者头尾重叠 while (a[head] <= flagNum && tail>head){ head++; } //head没和tail重叠时,交换两数位置 if (head < tail){ temp = a[head]; a[head] = a[tail]; a[tail] = temp; } } //当head和tail重叠(因为已经跳出循环了),交换flagNum和当前坐标 temp = a[0]; a[0] = a[tail]; a[tail] = temp; //head把数组分成2份,这里用递归(head可以换成tail,毕竟重叠了) quickSort(a, head); quickSort(a + head + 1, len - head - 1); return;}void main() { int *a; int numCount; int i; printf("input numCount\n"); scanf("%d", &numCount); a = (int *)malloc(sizeof(int) * numCount); printf("Now you input\n"); for (i = 0; i < numCount; ++i) { scanf("%d", &a[i]); } printf("sort before:"); for (i = 0; i < numCount; ++i) { printf("%d ",a[i]); } //快速排序算法开始 quickSort(a, numCount); printf("\nsort after:"); for (i = 0; i < numCount; ++i) { printf("%d ",a[i]); }}
阅读全文
1 0
- 排序算法_2,快速排序
- 排序_2.快速排序
- 交换排序_2.快速排序
- 排序算法--快速排序
- 排序算法--快速排序
- 排序算法---快速排序
- 排序算法-快速排序
- 排序算法------快速排序
- 排序算法---快速排序
- 排序算法-快速排序
- 排序算法---快速排序
- 排序算法--快速排序
- 排序算法--快速排序
- 排序算法--快速排序
- 排序算法:快速排序
- 排序算法 快速排序
- 排序算法--快速排序
- 排序算法--快速排序
- C++中的4种类型转换
- session详解
- PPT这样学就对了之目录页制作
- Mybatis入门学习(二)
- [嵌入式Linux驱动]S5PV210的蜂鸣器Linux驱动
- 排序算法_2,快速排序
- 关于引用(一)
- 2018网易--游历魔法王国
- HDU-6213-Chinese Zodiac(水题)
- 两个有序链表序列的合并
- 动态规划——旅行推销员问题
- Android中使用Activity管理类
- Step by Step——数据库-char & varchar & nvarchar
- 快速排序【递归分治法】