Reputation: 415
I am trying to search the integers "boxed" into the ArrayList and put the lowest value into the front of the list. However, it seems it's not placing it in the front when there is a new min.
Here are some examples: For example, if a variable called list stores the following values: {3, 8, 92, 4, 2, 17, 9} and you make this call: minToFront(list); it should store the following values after the call: {2, 3, 8, 92, 4, 17, 9} It is assumed that the list stores at least one value.
private static void minToFront(ArrayList<Integer> thing) {
int tempMin = Integer.MAX_VALUE;
for (int i = 0; i < thing.size(); i++) {
if (tempMin < thing.get(i)) {
thing.add(0,thing.get(i));
thing.remove(i+1);
i++;
}
}
}
Upvotes: 1
Views: 467
Reputation: 1
public static void minToFront(ArrayList<Integer> arrayList){
if(arrayList.size() == 0) {
System.out.println("Array is empty");
}
else {
int min = arrayList.get(0);
int index = 0;
for (int i = 0; i < arrayList.size(); i++) {
if (arrayList.get(i) < min)
min = arrayList.get(i);
}
index = arrayList.indexOf(min);
arrayList.remove(index);
arrayList.add(0, min);
}
}
input: [3, 8, 92, 4, 2, 17, 9]
output: [2, 3, 8, 92, 4, 17, 9]
Upvotes: 0
Reputation: 129477
Your logic is slightly off. Take a look at your if-statement:
if (tempMin < thing.get(i)) {
You're asking if the list element is greater than the maximum int value, which can never be true. You need to fully traverse the list once to find the minimum and its location, and then manipulate the list.
if (thing.size() < 2) // special case
return;
int min = thing.get(0), minLoc = 0;
for (int i = 1; i < thing.size(); i++) {
int next = thing.get(i);
if (next < min) {
min = next;
minLoc = i;
}
}
thing.add(0, thing.remove(minLoc));
Upvotes: 3