1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
|
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int partition(int *A, int l, int r)
{
int i, j, x, p;
p = A[l];
i = l + 1;
for(j=l+1;j<=r;j++)
{
if(A[j]<p)
{
x = A[j];
A[j] = A[i];
A[i] = x;
i++;
}
}
x = A[i-1];
A[i-1] = A[l];
A[l] = x;
cout<<i-1<<" "<<A[i-1]<<endl;
return i-1;
}
int RSelect(int *A, int l, int r, int i)
{
int p;
cout<<i<<" ";
if(l-r==0)
{
cout<<"wibble";
return A[l];
}
p = partition(A, l, r);
if(p==i)
{
cout<<"plibble"<<A[p]<<endl;
return A[p];
}
else if(p>i)
RSelect(A, l, p, i);
else if(p<i)
RSelect(A, p+1, r, i);
}
int main(int argc, char *argv[])
{
int i = 0, j, A[10000], k, p;
for(k=0;k<10000;k++)
A[k]=0;
fstream input;
input.open ("QuickSort.txt", fstream::in | fstream::out);
if (input.is_open())
{
while(input.good())
{
input >> j;
A[i] = j;
i++;
}
}
else
cout << "Error opening file\n";
input.close();
cout <<i<<" Which index element do you want? ";
cin >> j;
for(k=0;k<i;k++)
cout <<A[k]<<endl;
p = RSelect(A, 0, i-1, j-1);
cout <<p<<" is the "<<j<<"th element of the array."<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}
|