I was trying to improve my self about algorithms.
So I've tried to reverse an array of integer values.
Here is my solution.
static int[] reverseArray(int[] arr){
int[] newArr =new int[arr.length];
for (int i = arr.length-1, j = 0; i>=0; i-- , j ){
newArr[j] = arr[i];
}
return newArr;
}
And this is the solution what i see as the answer on the site. So my mind is little confused. In my opion my solution is easier and better. I don't understand why we have to divide it in two for example I think it's not necessary. So can anyone help me what's wrong with my solution?
for(int i = 0; i < my_array1.length / 2; i )
{
int temp = my_array1[i];
my_array1[i] = my_array1[my_array1.length - i - 1];
my_array1[my_array1.length - i - 1] = temp;
}
CodePudding user response:
On the one hand, your algorithm needs twice as much memory as the other. Since you are creating a copy of the array, if the length of the array is 50, you need to reserve 50 more memory addresses. However, the other solution just will need to reserve 1 memory address (for 1 auxiliar int
) regardless of the length of the original array.
On the other hand, your algorithm iterates all elements of the array while the other just needs to iterate to the midpoint.
Theoretically, both solutions have the same order of efficiency: O(n)
but in reality the other solution does fewer iterations.