zoukankan      html  css  js  c++  java
  • 快速排序非递归版本

    用栈记录每次要排序的左端点和右端点。

     1 int Partition(int a[], int f, int l) {
     2     int i = f - 1;
     3     for (int j = f; j < l; j++)
     4     {
     5         if (a[j] <= a[l]) {
     6             i++;
     7             swap(a[i], a[j]);
     8         }
     9     }
    10     i++;
    11     swap(a[i], a[l]);
    12     return i;
    13 }
    14  
    15 void QuickSort(int a[], int f, int l) {
    16     if (f >= l)
    17         return;
    18     stack<int> s;
    19     s.push(f);
    20     s.push(l);
    21 
    22     while (!s.empty())
    23     {
    24         int right = s.top();
    25         s.pop();
    26         int left = s.top();
    27         s.pop();
    28         if (left < right)
    29         {
    30             int p = Partition(a, left, right);
    31             // 左区间
    32             s.push(left);
    33             s.push(p - 1);
    34             // 右区间
    35             s.push(p + 1);
    36             s.push(right);
    37         }
    38     }
    39 }
  • 相关阅读:
    C#基础
    自动化测试
    C# 数据结构题目
    .NET基础知识
    Sharepoint题目
    题目总结2
    数据库索引
    题目总结(2014-1-10)
    Stack详解
    SpringBoot入门基础知识点
  • 原文地址:https://www.cnblogs.com/wmx24/p/9816858.html
Copyright © 2011-2022 走看看