Write a java program that calls a method that accepts an ArrayList of integer va
ID: 3733053 • Letter: W
Question
Write a java program that calls a method that accepts an ArrayList of integer values as a parameter and sorts each successive sequence of four values in the list in the descending order. If the list has extra values that are not part of a sequence of four, those values are unchanged. For example if a list stores values [10, 13, 2, 8, 7, 90, - 1, 2, 4, 5], after the call the list should store the values [13, 10, 8, 2, 90, 7, 2, 1, 4, 5]. The first sequence of four (10, 13, 2, 8) has been rearranged to (13, 10, 8, 2). The second sequence (7, 90, -1, 2) has been rearranged to (90, 7, 2, 1) and so on. Notice that 4 and 5 are unchanged because they were not part of a sequence of four values. Print the array before the call and after the call.
Explanation / Answer
ArrayListSortDemo.java
import java.util.ArrayList;
public class ArrayListSortDemo {
public static void main(String[] args) {
//Creating an ArrayList which hold Integers
ArrayList<Integer> arl = new ArrayList<Integer>();
arl.add(10);
arl.add(13);
arl.add(2);
arl.add(8);
arl.add(7);
arl.add(90);
arl.add(-1);
arl.add(2);
arl.add(4);
arl.add(5);
//Displaying the ArrayList before Sorting
System.out.println("Before Sorting :");
for (int i = 0; i < arl.size(); i++) {
System.out.print(arl.get(i) + " ");
}
sort(arl);
//Displaying the ArrayList after Sorting
System.out.println(" After Sorting :");
for (int i = 0; i < arl.size(); i++) {
System.out.print(arl.get(i) + " ");
}
}
//This Method will sort the sequence of each 4 integers in descending order
private static void sort(ArrayList<Integer> arl) {
int n, k = 0, i, h = 4, j, m = 0;
n = arl.size() / 4;
int temp1;
while (k < n) {
for (i = m; i < h; i++) {
for (j = i + 1; j < h; j++) {
if (arl.get(i) < arl.get(j)) {
temp1 = arl.get(i);
arl.set(i, arl.get(j));
arl.set(j, temp1);
}
}
}
h *= 2;
k++;
m += 4;
}
}
}
__________________
Output:
Before Sorting :
10 13 2 8 7 90 -1 2 4 5
After Sorting :
13 10 8 2 90 7 2 -1 4 5
_______________Thank You
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.