nth_element.pass.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. // <algorithm>
  10. // template<RandomAccessIterator Iter>
  11. // requires ShuffleIterator<Iter>
  12. // && LessThanComparable<Iter::value_type>
  13. // void
  14. // nth_element(Iter first, Iter nth, Iter last);
  15. #include <algorithm>
  16. #include <cassert>
  17. void
  18. test_one(unsigned N, unsigned M)
  19. {
  20. assert(N != 0);
  21. assert(M < N);
  22. int* array = new int[N];
  23. for (int i = 0; i < N; ++i)
  24. array[i] = i;
  25. std::random_shuffle(array, array+N);
  26. std::nth_element(array, array+M, array+N);
  27. assert(array[M] == M);
  28. delete [] array;
  29. }
  30. void
  31. test(unsigned N)
  32. {
  33. test_one(N, 0);
  34. test_one(N, 1);
  35. test_one(N, 2);
  36. test_one(N, 3);
  37. test_one(N, N/2-1);
  38. test_one(N, N/2);
  39. test_one(N, N/2+1);
  40. test_one(N, N-3);
  41. test_one(N, N-2);
  42. test_one(N, N-1);
  43. }
  44. int main()
  45. {
  46. int d = 0;
  47. std::nth_element(&d, &d, &d);
  48. assert(d == 0);
  49. test(256);
  50. test(257);
  51. test(499);
  52. test(500);
  53. test(997);
  54. test(1000);
  55. test(1009);
  56. }