Given an array of integers, sort the array into a wave like array and return it, In other words, arrange the elements into a sequence such that a1 >= a2 <= a3 >= a4 <= a5.....
Example
Given
[1, 2, 3, 4]
One possible answer:
[2, 1, 4, 3]
Another possible answer :[4, 1, 3, 2]
NOTE: If there are multiple answers possible, return the one thats lexicographically smallest. So, in example case, you will return
[2, 1, 4, 3]
My approach:
public class Solution {
public ArrayList<Integer> wave(ArrayList<Integer> A) {
Collections.sort(A);
int swap1, swap2,temp1,temp2;
//We will have to swap all the odd numbered elements with the even numbered elements
//such that all numbers with a gap 0f 1 are sorted
for( swap1= 0, swap2 = swap1 + 1; swap1 <= A.size()- 2; swap1 = swap1+2,swap2 = swap2+2 )
{
//Check if swap1 reaches last element
if( (swap1 == A.size() - 1) || (swap2 == A.size()) )
break;
else
{
temp1 = A.get(swap1);
temp2 = A.get(swap2);
A.set(swap1,temp2);
A.set(swap2, temp1);
}
}
return A;
}
}
I have the following questions regarding my code:
How can I further optimize my code? (I am unable to solve these questions within the prescribed time limit. What can I do?)
Is there any better approach to do this question?
Have I violated any convention in coding?
Are there any redundancies in my approach?