aman.wardak
BAN USERBalaji, that's not going to work because a HashMap doesn't guarantee storage of the items in the same order that you inserted them. You should use LinkedHashMap.
- aman.wardak December 24, 2015This solution is O(n/2) if input array is already sorted. Yes, that's the same as O(n) theoretically but in practice, n and n/2 could make a lot of difference for large n.
int *maxmin(int arr[], int size)
{
// sort array in ascending order if not already sorted
// create new array
int *outputarr = new int [size];
int i, j;
for (i=0, j=size-1; i <= j; i++, j--)
{
outputarr[i*2] = arr[j];
if (i == j) break; // so we don't write outside of array
outputarr[i*2+1] = arr[i];
}
return outputarr;
}
I think you need to use absolute values of a and b for the optimization to work for negative numbers as well:
if (abs(a) > abs(b)) {
swap(a, b);
}
...
- aman.wardak December 28, 2015