Quicksort

来源:互联网 发布:萤石云软件下载 编辑:程序博客网 时间:2024/06/05 15:07
#include <iostream>#include <fstream>#include <math.h>using namespace std;void PivotRules(int *arr, int n, int method){switch (method){case 1:{// ----- select the first element ------break;}case 2:{// ------ select the last element -----int temp;temp = arr[n-1];arr[n-1]=arr[0];arr[0] = temp;break;}case 3:{// ----- select the median element -----int temp;int mid = (n-1)/2;int med = 0;if ((arr[0] <= arr[mid] & arr[mid] <= arr[n-1]) || (arr[0] >= arr[mid] & arr[mid] >= arr[n-1]))med = mid;else if ((arr[mid] <= arr[0] & arr[0] <= arr[n-1]) || (arr[mid] >= arr[0] & arr[0] >= arr[n-1]))med = 0;elsemed = n-1;if (med != 0){temp = arr[0];arr[0] = arr[med];arr[med] = temp;}break;}default:{std::cout << "error";}}}int quicksort(int *arr, int n, int ncp, int method){if (n < 2)return ncp;ncp += n-1;PivotRules(arr, n, method);int temp;int ll = 1;int rr = 1;while (rr <n){if (arr[rr] < arr[0]){temp = arr[ll];arr[ll] = arr[rr];arr[rr] = temp;ll++;}rr++;}// -------  exchange ------temp = arr[ll-1];arr[ll-1] = arr[0];arr[0] = temp;// -------  split -----------ncp = quicksort(arr, ll-1, ncp, method);ncp = quicksort(arr+ll, n-ll, ncp, method);return ncp;}int main(){/*int arr[6] = {4,2, 5, 6, 1, 3};int n = 6;*/ifstream infile;infile.open("QuickSort.txt");int arr[100020];int temp[100020];int* ptr = &arr[0];int n=0;while(!infile.eof()){infile>>*ptr;ptr++;n++;}int ncp = 0;ncp = quicksort(arr, n-1, ncp, 3);cout << ncp << endl;infile.close();return 0;}

0 0
原创粉丝点击