Alternative Sorting in C++


Sorting the elements of an integer array in such a way that the first element is the maximum of the array and the second element of the sorted array is the minimum, the third one is the second minimum, the fourth one is the second maximum of the array and goes on.

Let’s take an example to understand the concept better,

Input : 4 1 8 2 9 3 7
Output : 9 1 8 2 7 3 4
Explanation : The elements in a sorted way is 1 2 3 4 7 8 9. Now, 
let’s create it in the manner we wanted it i.e. alternate sorted form. 
So, the largest element of the array first i.e. 9 followed by 1 which 
is the smallest element of the array i.e. 1 next comes 8 , 2 , 7 , 3, 4.

Now as we have understood the concept, we can develop a solution to address this issue. So, one possible solution would be sorting the array and print the last and first elements of this sorted array. Let's create an algorithm based on this solution.

Algorithm

Step 1 : Sort the array.
Step 2 : Create two pointers one for traversing from start and other pointer for traversing from end.
Step 3 : Print values of the pointer in alternate form and increase the value of the iterator.

Example

 Live Demo

#include <iostream>
using namespace std;
void alternateSort(int arr[], int n) ;
void swap(int *xp, int *yp) ;
void selectionSort(int arr[], int n) ;
int main(){
   int arr[] = { 4,1,8,2,9,3,7};
   int n = sizeof(arr)/sizeof(arr[0]);
   alternateSort(arr, n);
   return 0;
}
void alternateSort(int arr[], int n){
   selectionSort(arr, n);
   int i = 0, j = n-1;
   while (i < j) {
      cout << arr[j--] << " ";
      cout << arr[i++] << " ";
   }
   if (n % 2 != 0)
      cout << arr[i];
}
void swap(int *xp, int *yp){
   int temp = *xp;
   *xp = *yp;
   *yp = temp;
}
void selectionSort(int arr[], int n){
   int i, j, min_idx;
   for (i = 0; i < n-1; i++){
      min_idx = i;
   for (j = i+1; j < n; j++)
      if (arr[j] < arr[min_idx])
         min_idx = j;
      swap(&arr[min_idx], &arr[i]);
   }
}

Output

9 1 8 2 7 3 4

Updated on: 16-Oct-2019

474 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements