The first mistake you've made is within your nested for
loop. the starting index (j
) for the inner loop should always start at i + 1
(one place ahead of the indexer i
) for each iteration of the outer for
loop not j = 1
as you've done.
Second, by having the condition j < arr.length-1
you'll always exclude the last element within the array.
change this:
for(int j = 1; j < arr.length-1; j++)
to this:
for(int j = i + 1; j < arr.length; j++)
Moving on, there seems to be several problems with your algorithm including your swap
functionality so, let's start again.
Selection sort is an in-place comparison-based algorithm in which the array is divided into two parts, the sorted part at the left end and the unsorted part at the right end. Initially, the sorted part is empty and the unsorted part is the entire array.
The smallest element is selected from the unsorted array and swapped with the leftmost element, and that element becomes a part of the sorted array. This process continues moving unsorted array boundary by one element to the right.
with that in mind, now we can start the algorithm.
public static void selectionSort(int[] arr){
for(int i = 0; i < arr.length-1; i++){
int minIndex = i; // smallest element index
for(int j = i + 1; j < arr.length; j++){
if(arr[j] < arr[i]){ // find smallest element
if(arr[j] < arr[minIndex])
minIndex = j; // update smallest element index
}
}
if(i != minIndex){ // swap
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
// print the result
Arrays.stream(arr).forEach(System.out::println);
}
as a side note, Selection sort complexities are of Ο(N2)
, where N
is the number of elements within the array.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…