zoukankan      html  css  js  c++  java
  • 快速排序

     1 /*
     2 时间:2015年9月26日21:34:10
     3 描述:对数组a[]中元素排序
     4 功能:快速排序
     5 */
     6 # include <stdio.h>
     7 
     8 int FindPos(int *, int, int);
     9 void QuickSort(int *, int, int);
    10 
    11 int main(void)
    12 {
    13     int i;
    14     int a[6] = {5, 8, 7, -9, 0, 6};
    15     QuickSort(a, 0, 5);//第二个参数是第一个元素的下标,第三个参数是最后一个元素的下标
    16 
    17     for (i=0; i<6; i++)
    18         printf("%d  ", a[i]);
    19     printf("
    ");
    20 
    21     return 0;
    22 }
    23 
    24 /*
    25 函数:void QuickSort(参数1, 参数2, 参数3)
    26 功能:快速排序的循环
    27 参数:1.数组地址。2.某一半元素的低位。3.高位
    28 返回值:无
    29 */
    30 void QuickSort(int * a, int low, int high)
    31 {
    32     int pos;
    33     if (low < high)
    34     {
    35         pos = FindPos(a, low, high);
    36         QuickSort(a, low, pos-1);
    37         QuickSort(a, pos+1, high);
    38     }
    39 }
    40 
    41 /*
    42 函数:int FindPos(参数1, 参数2, 参数3)
    43 功能:查找a[low]的位置
    44 参数:1.数组地址。2.某一半元素的低位。3.高位
    45 返回值:a[low]的位置,int型
    46 */
    47 int FindPos(int * a, int low, int high)
    48 {
    49     int val = a[low];
    50     while (low < high)
    51     {
    52         while (low < high && a[high] > val)//注意此处low < high不能丢!
    53             high--;
    54         a[low] = a[high];
    55         while (low < high && a[low] < val)
    56             low++;
    57         a[high] = a[low];
    58     }//循环终止时,low = high
    59     a[low] = val;
    60     return low;
    61 }
    62 
    63 /*
    64 在VC++6.0输出结果是:
    65 ----------------------------
    66 -9  0  5  6  7  8
    67 Press any key to continue
    68 ----------------------------
    69 */
    http://www.cnblogs.com/moon1992/
  • 相关阅读:
    软件的命名方式
    游戏软件的发展和特点
    第一章 【概论】练习与讨论 第二题
    进行博客博文管理的设计
    可视化编程是否会慢慢取代目前的主流编程
    第二次作业(软件工作量的估记方法)
    第一次作业
    string字符串格式化成time_t,并计算2个time_t的时间差
    CSV简单解析与排序输出
    jqchart总结
  • 原文地址:https://www.cnblogs.com/moon1992/p/4855239.html
Copyright © 2011-2022 走看看