Write an application in Java which includes an algorithm that takes an array of
ID: 3788043 • Letter: W
Question
Write an application in Java which includes an algorithm that takes an array of any size, selects the high and low integer from the array of integers with each pass and builds a new array of integers by inserting the high and low selection with each pass. Your output should show the original array of integers and the output of each pass on a new line.
Note: You can assume all integers are positive, but your code must work for an even and odd number of
integers and an array of size from 5 to 30.
Example Output:
Input Array: [ 42 , 24, 7, 13, 36, 52]
Pass 1: [7, 52]
Pass 2: [7, 13, 42, 52]
Pass 3: [7, 13, 24, 36, 42, 52]
Explanation / Answer
Java Code :
import java.util.*;
import java.io.*;
public class HighLowPass{
public static Scanner s = new Scanner(System.in);
static int tempArray2[] = {};
public static void main(String []args){
System.out.println("Enter the array size");
int size = s.nextInt();
int[] numbers = new int[size];
System.out.println("Enter the array elements");
for(int i=0;i<numbers.length;i++){
numbers[i] = s.nextInt();
}
arrayPass(numbers);
}
public static void arrayPass(int numbers[]){
int[] tempArray = numbers;
tempArray = ascendingArray(tempArray);
for(int i=0;i<tempArray.length/2;i++){
lowHighArrayPass(tempArray[i],tempArray[tempArray.length-1-i]);
}
if(tempArray.length%2 != 0 ){
lowHighArrayPass(tempArray[tempArray.length/2],-1);
}
}
public static void lowHighArrayPass(int low , int high){
int tempArray[] = {low,high};
tempArray = mergeArrays(tempArray,tempArray2);
tempArray = ascendingArray(tempArray);
tempArray2 = tempArray;
System.out.print("Pass : [");
for(int a : tempArray){
if(a!=-1) System.out.print(a+" ");
}
tempArray2 = tempArray;
System.out.print("] ");
}
public static int[] ascendingArray(int[] tempArray){
for(int i=0;i<tempArray.length;i++){
for(int j=0;j<tempArray.length;j++){
if(tempArray[i]<tempArray[j]){
int temp = tempArray[i];
tempArray[i] = tempArray[j];
tempArray[j] = temp;
}
}
}
return tempArray;
}
public static int[] mergeArrays(int a[], int b[]){
int temp[] = new int[a.length+b.length];
int i=0;
for(int element : a){
temp[i++] = element;
}
for(int element : b){
temp[i++] = element;
}
return temp;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.