I assume you want the following algorithm: find min in the rest of the array, swap it with current element starting with first, reconsider rest to be array starting of increased +1 index.
You should update your code like this:
public static void swap(List<Integer> sort, int i, int j) {
int tmp = sort.get(i);
sort.set(i, sort.get(j));
sort.set(j, tmp);
}
public static void doSort(List<Integer> sort) {
int min;
for (int i = 0; i < sort.size(); ++i) {
//find minimum in the rest of array
min = i;
for (int j = i + 1; j < sort.size(); ++j) {
if (sort.get(j) < sort.get(min)) {
min = j;
}
}
//do swap
swap(sort, i, min);
}
}
You have a bug with finding minimum and then swapping items. Please note that the code can be improved in many ways (I tried to maintain your let's say way of coding as possible), such as swapping integer references in swap()
, doing BubbleSort
like another answer suggests (same algorithm but simpler implementation), using O(n * log(n))
complexity algorithm, and so on.