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/
  • 相关阅读:
    关于DOM节点的逆序
    javascript 巧妙的数组去重
    Canvas 学习笔记1
    web前端开发规范
    关于使用new和不使用new
    先知JS分享第二讲 数据类型与操作符
    关于谷歌console的小技巧
    菜鸟读jQuery 2.0.3 源码分析系列(2)
    菜鸟读jQuery 2.0.3 源码分析系列(1)
    local npm module ("*****") not found
  • 原文地址:https://www.cnblogs.com/moon1992/p/4855239.html
Copyright © 2011-2022 走看看