quickSort
来源:互联网 发布:瘦脸针 皮肤松弛 知乎 编辑:程序博客网 时间:2024/06/16 22:09
快速排序,通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。实现代码如下。
/*************************************************** quickSort.c *** 快速排序的实现*************************************************/#include <stdio.h>#define CUTOFF3void swap( int *x, int *y ){int nTmp = 0;nTmp = *x;*x = *y;*y = nTmp;}/***** 三数中值分割法**/int medin3( int A[], int nLeft, int nRight ){int nCenter = 0;nCenter = ( nLeft + nRight ) / 2;/*****使 A[nLeft] <= A[nCenter] <= A[nRight]**/if ( A[nLeft] > A[nCenter] ){swap( &A[nLeft], &A[nCenter] );}if ( A[nLeft] > A[nRight] ){swap( &A[nLeft], &A[nRight] );}if ( A[nCenter] > A[nRight] ){swap( &A[nCenter], &A[nRight] );}swap( &A[nCenter], &A[nRight-1] );/** 在位置nRight-1放置枢纽元 **/returnA[nRight-1];}void insertSort( int A[], int n ){int i = 0;int j = 0;int nTmp = 0;for (i=1; i<n; i++){nTmp = A[i];for (j=i; j>0 && A[j-1]>nTmp; j--){A[j] = A[j-1];}A[j] = nTmp;}}void QSort( int A[], int nLeft, int nRight ){int nPovit = 0;int i = 0;int j = 0;if ( nLeft + CUTOFF <= nRight )/** 设置调用快速排序的条件 **/{nPovit = medin3( A, nLeft, nRight );i = nLeft;j = nRight - 1;for ( ; ; ){while ( A[++i] < nPovit )/** i跳过小于nPovit的数 **/;while ( A[--j] > nPovit )/** j跳过大于nPovit的数 **/;if ( i < j )/** 若i<j, 则交换对应位置的元素 **/{swap( &A[i], &A[j] );}else{break;}}swap( &A[i], &A[nRight-1] );/** 存放枢纽元 **/QSort( A, nLeft, i - 1 );/** 快排枢纽元左边的数 **/QSort( A, i + 1, nRight );/** 快排枢纽元右边的数 **/}else{insertSort( A + nLeft, nRight - nLeft + 1 );/** 若待排数小于4则调用插入排序 **/}}void quickSort( int A[], int n ){QSort( A, 0, n - 1 );}int main(){int i = 0;int n = 10;int nArray[10] = {8, 1, 4, 9, 0, 3, 5, 2, 7, 6};printf("The arrry before quickSort is: \n");for (i=0; i<n; i++){printf("%d ", nArray[i]);}printf("\n\n");quickSort( nArray, n );/** 调用快速排序 **/printf("The arrry after quickSort is: \n");for (i=0; i<n; i++){printf("%d ", nArray[i]);}printf("\n");return0;}
- Quicksort
- QuickSort
- quicksort
- quicksort
- QuickSort
- QuickSort
- QuickSort
- QuickSort
- QuickSort
- QuickSort
- quicksort
- QuickSort
- QuickSort
- QuickSort
- quicksort
- quicksort
- QuickSort
- Quicksort
- RTP/RTCP的实现
- 计算距离国庆多少天
- mysql下载、安装、启动、使用、卸载、常见错误
- 日志记录过滤器
- mysql数据库中日期类型为datetime,而用mybatis映射失败,报java.sql.SQLException: Cannot convert value '0000-00-00 00:00:
- quickSort
- Lua的数据结构
- Filter(过滤器)简介和工作原理
- JSP pageEncoding charset 区别
- ERROR 1005 (HY000): Can't create table 'XXXXX' (errno: 150)
- NSBundle介绍
- C++ typedef用法小结
- 目标检测的图像特征提取之(一)HOG特征——http://blog.csdn.net/zouxy09/article/details/7929348
- CodeForces 111B - Petya and Divisors 统计..想法题