problem no 62:(problem on array):wave array.

problem:

 

Given a sorted array arr[] of distinct 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..... (considering the increasing lexicographical order).

Example 1:

Input:
n = 5
arr[] = {1,2,3,4,5}
Output: 2 1 4 3 5
Explanation: Array elements after 
sorting it in wave form are 
2 1 4 3 5.

 

Example 2:

Input:
n = 6
arr[] = {2,4,7,8,9,10}
Output: 4 2 8 7 10 9
Explanation: Array elements after 
sorting it in wave form are 
4 2 8 7 10 9.

 

 

 

 code:

 

   void swap(int *x, int *y)
{
    int temp = *x;
    *x = *y;
    *y = temp;
}


    void convertToWave(int *arr, int n){
       
       sort(arr, arr+n);
 
  
    for (int i=0; i<n-1; i += 2)
        swap(&arr[i], &arr[i+1]);  
       
    } 


Comments

Popular posts from this blog

problem 3: given two integers N and M. The problem is to find the number closest to N and divisible by M. If there are more than one such number, then output the one having maximum absolute value.

problem no 7:Given two numbers A and B, find Kth digit from right of AB.

Problem no 16: count the number of squares below N.