Coders Packet

Alternate sorting on even size data set using C++

By Vanshika Vaidya

In this article, We are going to learn how to sort the array using an alternate sorting algorithm.

Sorting an array means reordering the integer array elements in ascending and descending order there are different sorting 

algorithms present like the bubble sort, selection sort, insertion sort, binary sort, radix sort, and so on.

There is one more sorting algorithm present that is an alternate sort.

Alternate sort arranges the given input sorted integer array in such a way that it prints the first maximum and minimum element of the array and then the second maximum and minimum element of the array and so on.

In the given code below the size of the array must be maximum.

Input : arr[] = {8, 1, 2, 3, 5, 6}
Output : 8 1 6 2 5 3 
#include
#include<bits/stdc++.h>
using namespace std;
void alternate_sort(int arr[],int n){
  sort(arr,arr+n);
  cout<<"After alternative sort :";
  if(n%2==0){
    for(int i=0;i<n;i++){
    cout<<arr[--n]<<" ";
    cout<<arr[i]<<" ";
    }
  }		
}


int main(){
  int n ;
  cout<<"Enter the size of data set (it must be an even number) ";
  cin>>n;
  if(n%2==0){
  int arr[n];
  for(int i=0;i<n;i++)
  cin>>arr[i];
  alternate_sort(arr,n);	
  }
  else 
  cout<<"Data set size must be even !! ";
  
  return 0;
}

 

Download project

Reviews Report

Submitted by Vanshika Vaidya (vaidya27)

Download packets of source code on Coders Packet