Your implementation is definitely similar to the selection sort, but the swap should happen outside the nested loop. Within the innermost loop you should only save the index of the smallest element among the ones left to sort (I've misread you if placement during my first editing of the answer).
The main difference between selection sort and bubble sort is mainly, but not entirely, in their nested loop. In fact, the selection sort tries in its nested loop to find the smallest element after i and then places it at the i-th position. In this way, at each iteration of the outer loop it is guaranteed that the i-th element corresponds to the smallest among the ones left to sort (from i to n-1).
public void selectionSort(int[] arr){
int temp, min;
// At every iteration, the outer loop checks whether the i-th element is already at the right place,
// i.e. being the smallest value among the ones that follow it
for (int i = 0; i < arr.length-1; i++) {
//Assuming that the element in position i is the smallest among the ones left to sort
min = i;
//At every iteration of the outer loop, the innermost loop checks if there's a smaller value than the one in position i
for (int j = i + 1; j < arr.length; j++) {
//If a smaller value than the min-th element is found then j is stored as the current smallest index
if (arr[min] > arr[j]) {
min = j;
}
}
//Swapping the smallest element found with the one in position i.
//If min is still equal to i then no actual swap happens
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
On the other hand, the bubble sort algorithm achieves the same thing but instead of traversing from left to right, it iterates from right to left carrying with it the new smallest element it encounters.
public void bubbleSort(int[] vet) {
int temp;
//At every iteration, the outermost loop checks if there are any elements after i which are smaller than it
for (int i = 0; i < vet.length - 1; i++) {
// The innermost loop starts from the right bound 'till the i index.
// Every time this loop finds in [j-1] a bigger element than the one in [j],
// then these two are swapped to carry along the smaller element in position j during the traverse.
// Instead if the element in [j-1] is smaller than the one in [j],
// then it leaves them like that and keeps carrying [j-1] along instead of [j].
for (int j = vet.length - 1; j >= i + 1; j--) {
if (vet[j] < (vet[j - 1])) {
temp = vet[j];
vet[j] = vet[j - 1];
vet[j - 1] = temp;
}
}
}
}
Arrays.sort(arr), importjava.util.Arrays