#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;
else
med = 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;
}
Quicksort
最新推荐文章于 2024-05-14 10:51:55 发布