Rearrange Array in Maximum-Minimum form
Given a sorted array of positive integers, rearrange the array alternately i.e first element should be the maximum value, second minimum value, third-second max, fourth-second min and so on. Naive Solution: Here we will use an auxiliary array to store the elements in correct order. For even indices of the array Large numbers from the given array are added. For odd indices small numbers are added. Code: import java.util.*; public class Test{ public static void main(String[] args) { Scanner in = new Scanner(System.in); int[] a = {1,2,3,4,5,6,7,8,9}; int n = a.length; int[] temp = new int[n]; int small = 0; int large = n-1; for(int i=0; i<n; i++){ if(i%2 == 0){ temp[i] = a[large--]; } else{ temp[i] = a[small++]; } } for(int i=0; i<n; i++){ System.out.print(temp[i]+" "); }
This comment has been removed by the author.
ReplyDeleteGood presentation and easy to understand 😀
DeleteThank u Mahasri😊
ReplyDelete