Alternate Sorting in java
Your are given with an array, now you need to show the output as -first maximum number followed by first minimum number followed by second maximum number and second minimum number and so on....
Input
7 ----Array size
1 -------------
2 |
3 |
4 |---Array elements
5 |
6 |
7 ------------
Output:
7
1
6
2
5
3
4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class AlternateSorting { | |
public static int[] alternateSorting(int[] input1) | |
{ | |
Arrays.sort(input1); | |
int len=input1.length; | |
int [] array=new int [len]; | |
int k=0,j=len,l=0; | |
while(k<len){ | |
if(k%2!=0){ | |
array[k]=input1[l]; | |
l++; | |
} | |
else{ | |
j--; | |
array[k]=input1[j]; | |
} | |
k++; | |
} | |
return array; | |
} | |
public static void main(String[] args) { | |
Scanner in = new Scanner(System.in); | |
int[] output = null; | |
int ip1_size = 0; | |
ip1_size = Integer.parseInt(in.nextLine().trim()); | |
int[] ip1 = new int[ip1_size]; | |
int ip1_item; | |
for(int ip1_i = 0; ip1_i < ip1_size; ip1_i++) { | |
ip1_item = Integer.parseInt(in.nextLine().trim()); | |
ip1[ip1_i] = ip1_item; | |
} | |
output = alternateSorting(ip1); | |
for(int output_i=0; output_i < output.length; output_i++) { | |
System.out.println(String.valueOf(output[output_i])); | |
} | |
in.close(); | |
} | |
} |
Input
7 ----Array size
1 -------------
2 |
3 |
4 |---Array elements
5 |
6 |
7 ------------
Output:
7
1
6
2
5
3
4
Comments
Post a Comment