Cod sursa(job #2246791)

Utilizator ptudortudor P ptudor Data 27 septembrie 2018 16:08:21
Problema Statistici de ordine Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.86 kb
#include <bits/stdc++.h>
using namespace std;
int n,k,a[3000005];
void Swap(int &x,int &y)
{
    int d=x;
    x=y;
    y=d;
}
int pivot(int st, int dr)
{int i, j, p, x;
  p =(st+dr)/2;  // p = rand() % (dr - st + 1) + st;

  swap(a[st], a[p]);
  x = a[st];
  i = st + 1;
  j = dr;
  while (i <= j)
  {
    if (a[i] <= x) i++;
    if (a[j] > x) j--;
    if (i < j && a[i] > x && x > a[j])
    {
        swap(a[i], a[j]);
        i++; j--;
    }
  }

  swap(a[i-1], a[st]);
  return i-1;

}
int main()
{int i,gasit=0,aux,st=1,dr;
    ifstream in("sdo.in");
    ofstream out("sdo.out");
    in>>n>>k;
    dr=n;
    for (i=1;i<=n;i++) in>>a[i];
pivot (st,dr);
    while (!gasit)
    {
        aux=pivot(st,dr);
        if (aux==k)
            {out<<a[aux]<<"\n"; gasit=1;}
        if (aux<k) st=aux+1;
        if (aux>k) dr=aux-1;
    }
}