Sort an array in alternative order
  • Posted: 6 years ago
  • Updated: 5 years ago
  • Edit
  • answers (1)
  • views (1586)

Suppose you are given an array of integers. How will you sort the array into alternative order?


Posted Answers

The algorithm works as :


  • Sort the array in ascending order.
  • Swap each pair of elements in the sorted array except the first element.

Time to sort the array is \( O(nlogn) \) and to swap is \( O(n) \). Therefore, overall time complexity = \( O(nlogn) \).

public static void sortInAlternateOrder(int[] array){

/* Sort the input array */
Arrays.sort(array);

/* Initialization */
/* Leave the 0th element and start from the 1st element of the sorted array */
int begin = 1;
int end = array.length - 1;

/* Swap each pair of elements */
while(begin < end){
swap(array[begin], array[begin + 1]);
begin = begin + 2;
}
}

public static void swap(int a, int b){
int temp = a;
a = b;
b = temp;
}

You need to Sign In to post your solution.