Algorithmic Implementation series(6) Implementation of Quick_Sort

来源:互联网 发布:杨幂和唐嫣友情知乎 编辑:程序博客网 时间:2024/06/05 20:11

Compiler: gcc 4.7.3

C++ Standard: C++0x

OS:CentOS 6.3 x86

  1 #include <iostream>
  2 
  3 using namespace std;
  4 
  5 //swap the ith element and the jth element in an array
  6 void swap_elements(int ia[], const size_t i, const size_t j) {
  7     if(i == j) { return; }
  8     const int tmp = ia[i - 1];
  9     ia[i - 1] = ia[j - 1];
 10     ia[j - 1] = tmp;
 11 }
 12 
 13 const size_t partition(int ia[], const size_t p,const size_t r) {
 14     //The value of variable x is the last element in array ia.
 15     const int x = ia[r - 1];
 16 
 17     //Variable i marks the position before the first element in
 18     //array ia.
 19     int i = p - 2;
 20 
 21     //The for loop goes from the first element inclusive to one
 22     //before the last element in array ia.
 23     for(size_t j = p; j != r; ++j) {
 24         if(ia[j - 1] <= x) {
 25             ++i;
 26             swap_elements(ia, i + 1, j);
 27         }
 28     }
 29     swap_elements(ia, i + 2, r);
 30     return i + 2;
 31 }
 32 
 33 void Quick_Sort(int ia[], const size_t p,const size_t r) {
 34     if(p < r) {
 35         const size_t q = partition(ia, p, r);
 36         Quick_Sort(ia, p, q - 1);
 37         Quick_Sort(ia, q + 1, r);
 38     }
 39 }
 40 
 41 int main() {
 42     int ia[] = {2, 32, 4, 6, -2, 4, 5, -55, -3, 55, 88};
 43     const size_t size = sizeof(ia)/sizeof(int);
 44 
 45     Quick_Sort(ia, 1, size);
 46 
 47     for(size_t i = 0; i != size; ++i) {
 48         cout << ia[i] << " ";
 49     }
 50     cout << endl;                                                                                   
 51 
 52     return EXIT_SUCCESS;
 53 }
 54