-1

This will find the nth element in an unsorted array as if it was sorted, and I want it to run below n log n time, but I'm not entirely sure the run time of this, would it be O(n^2)?

int nthElement(std::vector<int> vec, int n)
{
  n--;
  int smallest = vec[0];
  int index = 0;
  for(int i = 0; i < vec.size(); i++)
  {
    if (vec[i] < smallest)
    {
      smallest = vec[i];
      index = i;
    }
  }
  vec.erase(vec.begin() + index);
  if( n == 0)
  {
    std::cout << "Do I get here?" << std::endl;
    return smallest;
  } 
  return nthElement(vec, n);
}
ggorlen
  • 44,755
  • 7
  • 76
  • 106
Evan W.
  • 67
  • 6

1 Answers1

0

Ask yourself what's n compared to vec.size(). Assuming n is kind of random between 0 and vec.size()-1, the following holds true:
- in the best case, n = 0.
- in the worst case, n = vec.size().
- in the average case, n ~ vec.size() (~ means proportional).

So the time complexity, in general, is indeed O(n^2) = O(vec.size()^2) = O(n*vec.size()).

Nelfeal
  • 12,593
  • 1
  • 20
  • 39