1

What's the runtime (in Big O notation) for Array reversal for the below java code?

void reverse(int[] array){
   for(int i=0;i<array.length/2;i++){
     int other = array.length-i-1;
     int temp = array[i];
     array[i] = array[other];
     array[other] = temp;
   }
}
Jarvis
  • 8,494
  • 3
  • 27
  • 58
Harry
  • 237
  • 2
  • 10
  • 4
    `O(n)` because it grows *linearly* with the length of `array`. – Elliott Frisch Feb 25 '17 at 02:17
  • 1
    Very obviously O(n), all operations are 1, and you loop with the size of the arr, even with O(n/2) = O(n) – buræquete Feb 25 '17 at 02:22
  • 1
    Simple approach. Count the operations performed for an array of size N. Is it proportional to N? If so, the algorithm is `O(N)`. – Stephen C Feb 25 '17 at 02:23
  • Thanks @StephenC. This is what I was not sure about if proportions are discarded or not. Thanks for confirming. – Harry Feb 25 '17 at 14:12
  • @Harry - If you weren't sure of that, then you should find / read a good explanation of what Big O notation actually means. – Stephen C Feb 25 '17 at 23:21

0 Answers0