I'm getting very frustrated from this problem I have. Here is the gist of what is happening:
import static java.lang.System.*;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(12);
list.add(19);
list.add(442);
list.add(3);
list.add(1);
list.add(9);
out.println(list.toString());
out.println(bubbleSort(list));
out.println(list.toString());
}
public static int bubbleSort(ArrayList<Integer> num) {
int j;
boolean flag = true;
int temp;
while(flag) {
flag = false;
for(j = 0; j < num.size() - 1; j++) {
if(num.get(j) > num.get(j + 1)) {
temp = num.get(j);
num.set(j, num.get(j + 1));
num.set(j + 1, temp);
flag = true;
}
}
}
return num.get(0);
}
}
The output is:
[12, 19, 442, 3, 1, 9]
1
[1, 3, 9, 12, 19, 442]
Why is the ArrayList list
getting sorted when I call the method bubbleSort()
? Shouldn't the method be making an instance of list
when I call it as bubbleSort(list)
and not sort list
itself which is outside its scope? I just want bubbleSort
to get the smallest value of list
by making an instance of list
, sorting that instance using bubble sort, and returning the first value of that instance. Am I missing something really obvious? I've gotten really tired from my frustration over this problem...