Write a JAVA application which includes an algorithm that takes an array, select
ID: 640175 • Letter: W
Question
Write a JAVA application which includes an algorithm that takes an array, 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.
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
public class ArrayTest {
public static void main(String args[]) {
int arr[] = { 42, 24, 7, 13, 36, 52 };
int arr1[] = new int[arr.length];
System.out.print("Input Array -> ");
for (int i = 0; i < arr.length; ++i) {
System.out.print(arr[i] + " ");
}
System.out.print(" ");
int min = 55555, max = -55555;
int minind = 0, maxind = 0;
int count = 0;
for (int i = 0; i < arr.length / 2; ++i) {
min = 55555;
max = -55555;
for (int j = 0; j < arr.length; ++j) {
if (min > arr[j] && arr[j] != -555) {
minind = j;
min = arr[j];
}
if (max < arr[j] && arr[j] != -555) {
maxind = j;
max = arr[j];
}
}
for (int j = count + 1; j >= (i + 2); --j) {
if ((j - 2) >= 0) {
arr1[j] = arr1[j - 2];
}
}
arr[minind] = -555;
arr[maxind] = -555;
arr1[i] = min;
arr1[i + 1] = max;
count += 2;
System.out.print("Pass " + (i + 1) + " -> ");
for (int j = 0; j < count; ++j) {
System.out.print(arr1[j] + " ");
}
System.out.print(" ");
}
if (arr.length % 2 == 1) {
int i = arr.length / 2;
for (int j = count; j >= (i + 1); --j) {
if ((j - 1) >= 0) {
arr1[j] = arr1[j - 1];
}
}
int temp = 0;
for (int j = 0; j < arr.length; ++j) {
if (arr[j] != -555) {
temp = arr[j];
}
}
arr1[arr.length / 2] = temp;
count += 1;
System.out.print("Pass " + ((arr.length / 2) + 1) + " -> ");
for (int j = 0; j < count; ++j) {
System.out.print(arr1[j] + " ");
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.