Pagini recente » Cod sursa (job #3167369) | Cod sursa (job #1689201) | Cod sursa (job #292367) | Cod sursa (job #1931229) | Cod sursa (job #2057836)
/// QuickSort
#include <iostream>
#include <fstream>
using namespace std;
ifstream in("sdo.in");
ofstream out("sdo.out");
const int N = 500000;
int v[N];
int n,desiredPosition;
void print(){
for(int i=0; i<n; ++i)
out<<v[i]<<" ";
out<<"\n";
}
int lowerThanPivot[N], greaterThanPivot[N];
int movePivot(int leftIndex, int rightIndex){ /// Consider "leftIndex" the pivot
int lengthLower = 0, lengthGreater = 0;
int pivot = v[leftIndex];
for(int i=leftIndex+1; i <= rightIndex; ++i)
if(v[i] < pivot)
lowerThanPivot[lengthLower++] = v[i];
else
greaterThanPivot[lengthGreater++] = v[i];
int pivotIndex = leftIndex + lengthLower;
for(int i=leftIndex; i<pivotIndex; ++i)
v[i] = lowerThanPivot[i - leftIndex];
v[pivotIndex] = pivot;
for(int i=pivotIndex + 1; i <= rightIndex; ++i)
v[i] = greaterThanPivot[i - pivotIndex - 1];
return pivotIndex;
}
void quickSort(int leftIndex, int rightIndex){
if(leftIndex >= rightIndex)
return;
int pivotIndex = movePivot(leftIndex, rightIndex);
//cout<<leftIndex<<", "<<rightIndex<<" | "<<pivotIndex<<"\n";
//print();
if(leftIndex <= desiredPosition && desiredPosition <= pivotIndex)
quickSort(leftIndex, pivotIndex);
else if(pivotIndex +1 <= desiredPosition && desiredPosition <= rightIndex)
quickSort(pivotIndex+1, rightIndex);
else /// Don't reach this point in the program, ever!
{
v[39453495] = 0;
}
}
int main()
{
in>>n>>desiredPosition;
--desiredPosition;
for(int i=0; i<n; ++i)
in>>v[i];
//print();
quickSort(0, n-1);
out<<v[desiredPosition];
return 0;
}