fork(1) download
  1. #include <iostream>
  2. using namespace std;
  3. int kth(int *arr, int l,int r,int k)
  4. {
  5. long long x = arr[(l+r) / 2];
  6. int i=l,j=r;
  7. while(i<=j)
  8. {
  9. while(arr[i] < x) i++;
  10. while(arr[j] > x) j--;
  11.  
  12. if(i<=j)
  13. {
  14. std::swap(arr[i],arr[j]);
  15. i++;
  16. j--;
  17. }
  18. }
  19. if(l<=k && k<=j)
  20. return kth(arr, l,j,k);
  21. if( i<=k && k<=r)
  22. return kth(arr, i,r,k);
  23. return arr[k];
  24. }
  25.  
  26. int main() {
  27. int a[4] = {3, 6, 4, 5};
  28. cout << kth(a, 0, 4, 1) << endl;
  29. cout << kth(a, 0, 4, 2) << endl;
  30. cout << kth(a, 0, 4, 3) << endl;
  31. cout << kth(a, 0, 4, 4) << endl;
  32. return 0;
  33. }
Runtime error #stdin #stdout 0s 3412KB
stdin
Standard input is empty
stdout
3
4
5
6