Write a java program that calls a method called reverse4 that accepts an ArrayLi
ID: 3733911 • Letter: W
Question
Write a java program that calls a method called reverse4 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
import java.io.*;
class reverseArray {
/* Function to sort in desc arr[] from start to end*/
static void rverese4(int a[], int start, int end)
{ int temp;
for (int i = start; i < end; i++)
{
for (int j = i + 1; j < end; j++)
{
if (a[i] < a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
/* Utility that prints out an array on a line */
static void printArray(int arr[], int size)
{
for (int i=0; i < size; i++)
System.out.print(arr[i] + " ");
System.out.println("");
}
/*Driver function to check for above functions*/
public static void main (String[] args) {
int arr[] = {10, 13,2,8,7,90,-1,2, 4, 5};
int size=10;
printArray(arr, size);
for (int i=0; i+4<size; i+=4)
rverese4(arr, i, i+4);
System.out.println("Reversed array is ");
printArray(arr, size);
}
}
OUTPUT:-
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.