仅作为记录,有空可以温故

使用了三种选择pivot的策略,前两种分别是1、选择第一个元素作为pivot;2、选择最后一个元素作为pivot;3、选择前、中、后三个元素中大小中等的元素作为pivot。其中前两种在注释里。


     
#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <ctime>
usingnamespace std;
unsigned longint comparNum = 0;
constint MAXN = 10000;
void QuickSort(int A[], int low, int high);
int Median3( int A[], int low, int high);
int Partition(int A[], int low, int high);
void swap( int *, int *);
int main()
{
    //read file,initial a integer vector
    time_t begin,end;
    begin = clock();
    ifstream fin("QuickSort");
    string cArr[MAXN];
    int arr[MAXN];
    for (int i = 0; i < MAXN; ++i)
    {
    getline(fin, cArr[i]);
    arr[i] = atoi(cArr[i].c_str());
  }
  fin.close();
  QuickSort(arr, 0, MAXN - 1);
  cout << "The number of comparisons is: " << comparNum <<endl;
  end = clock();
  cout << "The running time is:" << double(end - begin)/CLOCKS_PER_SEC <<endl;
return 0;
}
void QuickSort(int A[], int low, int high)
{
if (low >= high)
return;
elseif (high - low == 1)
  {
    comparNum += 1;
if(A[ low ] > A[ high ])
      swap(&A[ low ], &A[ high ]);
  }
else
  {
int pivot_loc = Partition(A, low, high);
    QuickSort(A, low, pivot_loc - 1);
    QuickSort(A, pivot_loc + 1, high);
  }
}
int Partition(int A[], int low, int high)
{
//#1
//int pivot = A[low];
//#2
//int pivot = A[high];
//swap(&A[low], &A[high]);
//#3
int pivot = Median3( A, low, high);
int i = low+1;
int j = low+1; //the most left
for (; j <= high; ++j) {
if ( A[j] < pivot) {
      swap( &A[j], &A[i]);
      ++i;
    }
  }
  swap(&A[low], &A[i-1]);
  comparNum += high - low;
return (i-1);
}
void swap( int *a, int *b)
{
int c = *a;
  *a = *b;
  *b = c;
}
int Median3( int A[], int low, int high)
{
int center = (low + high) / 2;
int temp[3] = {A[ low ], A[ center ], A[ high ]};
if (temp[0] > temp [1])
    swap(&temp[0], &temp[1]);
if (temp[0] > temp [2])
    swap(&temp[0], &temp[2]);
if (temp[1] > temp [2])
    swap(&temp[1], &temp[2]);
//Invariant: temp[0] <= temp[1] <= temp[2]
if (A[ center ] == temp[ 1 ])
    swap(A[ center ], A[ low ]);
elseif (A[ high ] == temp[ 1 ])
    swap(A[ high ], A[ low ]);
return A[ low ];
}
51的自动打乱排版功能非常不错。