Really need help with this, thanks! a. Method minToFront: takes an ArrayList of
ID: 3794389 • Letter: R
Question
Really need help with this, thanks!
a. Method minToFront: takes an ArrayList of integers as a parameter. The method moves the minimum value in the list to the front, otherwise preserving the order of the elements. For example, if a variable called list stores the following values: [4, 7, 9, 2, 7, 7, 5, 3, 5, 1, 7, 8, 6, 7] and you make this call: minToFront(list); it should store the following values after the call: [1, 4, 7, 9, 2, 7, 7, 5, 3, 5, 7, 8, 6, 7]. You may assume that the list stores at least one value. After the call print the list.
Explanation / Answer
Hi, Please find my implementation.
Please let me know in case of any issue.
import java.util.ArrayList;
public class ArrayListTest {
public static void minToFront(ArrayList<Integer> list){
// finding the index of minimum element
int min_index = 0;
for(int i=1; i<list.size(); i++)
if(list.get(i) < list.get(min_index))
min_index = i;
// removing minimum elements and adding at front
int min = list.get(min_index);
list.remove(min_index);
list.add(0, min);
}
public static void main(String[] args) {
int ar[] = {4, 7, 9, 2, 7, 7, 5, 3, 5, 1, 7, 8, 6, 7};
ArrayList<Integer> list =new ArrayList<>();
list.add(4);
list.add(7);
list.add(9);
list.add(2);
list.add(7);
list.add(7);
list.add(5);
list.add(3);
list.add(5);
list.add(1);
list.add(7);
list.add(8);
list.add(6);
list.add(7);
System.err.println(list);
minToFront(list);
System.err.println(list);
}
}
/*
Sample run:
[4, 7, 9, 2, 7, 7, 5, 3, 5, 1, 7, 8, 6, 7]
[1, 4, 7, 9, 2, 7, 7, 5, 3, 5, 7, 8, 6, 7]
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.