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

    1、算法导论描述

      参见《算法导论》对快速排序的伪代码描述:

      关键代码:

      模拟过程表示:

    2、C++实现

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <time.h>
     4 
     5 #define DATA_LEN 20
     6 
     7 void PrintData(int data[], int start_index, int end_index) {
     8     printf("DATA[%d, %d]:", start_index, end_index);
     9     for (int i = 0; i < DATA_LEN; ++i) {
    10         printf("%d ", data[i]);
    11     }
    12     printf("
    ");
    13 }
    14 
    15 void Swap(int szData[], int i, int j) {
    16     printf("[%d] %d <-> [%d] %d
    ", i, szData[i], j, szData[j]);
    17     int temp = szData[i];
    18     szData[i] = szData[j];
    19     szData[j] = temp;
    20 }
    21 
    22 int Partition(int szData[], int startIndex, int endIndex) {
    23     PrintData(szData, startIndex, endIndex);
    24     int guard = szData[endIndex];
    25     int i = startIndex - 1;
    26     int j = startIndex;
    27     for (; j < endIndex; ++j) {
    28         if (szData[j] <= guard) {
    29             ++i;
    30             Swap(szData, i, j);
    31         }
    32     }
    33 
    34     Swap(szData, endIndex, i + 1);
    35     return i + 1;
    36 }
    37 
    38 void QuickSort(int szData[], int startIndex, int endIndex) {
    39     if (startIndex < endIndex) {
    40         int j = Partition(szData, startIndex, endIndex);
    41         QuickSort(szData, startIndex, j - 1);
    42         QuickSort(szData, j + 1, endIndex);
    43     }
    44 }
    45 
    46 int main()
    47 {
    48     srand((unsigned)time(NULL));
    49 
    50     int origin_data[DATA_LEN] = { 0 };
    51     printf("ORIGIN:");
    52     for (int i = 0; i < DATA_LEN; ++i) {
    53         origin_data[i] = rand() % 100;
    54         printf("%d ", origin_data[i]);
    55     }
    56     printf("
    ");
    57 
    58     QuickSort(origin_data, 0, DATA_LEN - 1);
    59 
    60     printf("SORTED:");
    61     for (int i = 0; i < DATA_LEN; ++i) {
    62         printf("%d ", origin_data[i]);
    63     }
    64     printf("
    ");
    65 
    66     system("pause");
    67     return 0;
    68 }
    View Code

    3、心得

      单游标一趟遍历,i总指向的是最后一个小于“卫兵”的值所在位置,j不断正向遍历至“卫兵”(最后元素)的倒数第二个。最后交换i+1与“卫兵”就对了!

  • 相关阅读:
    table布局与div布局
    HTML一般标签
    jquery
    PDO对象
    分页例题
    投票练习
    封装 链接数据库类
    访问数据方法
    面相对象多态
    面向对象
  • 原文地址:https://www.cnblogs.com/kuliuheng/p/10553504.html
Copyright © 2011-2022 走看看