I have some questions about selection sort.I\'m a little bit confused.
int [] arr = {5,4,3,2,1}; // This is my array
int min = 0;
for(int i = 0;i&l
int[] arr = {5,4,3,2,1};
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++)
if (arr[j] < arr[index])
index = j;
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
This is the correct method for selection sort The thing you have been doing wrong is you are swapping within the inner loop but actually the swapping needs to be done after the first complete round of inner loop where the minimum element is determined.
Just pass array and size of array
private void selectionSort() {
for (int i = 0; i < arraySize; i++) {
for (int j = i; j < arraySize; j++) {
if (array[i] > array[j])
swapValues(i,j);
}
}
}
private void swapValues(int posOne, int posTwo) {
int tValue = array[posOne];
array[posOne] = array[posTwo];
array[posTwo] = tValue;
}
You should start by assuming that the first element is the smallest one, then iterate over the array and if you find a smaller element, remember that position and assume that is the smallest one. When you get to the end of the array you should know the position of the smallest value. Switch that value with the value at the first position. Now the smallest value is first. Start at next position, assume that is the smallest value, iterate over the rest of the array... (I think you get the idea.
Example:
3,1,2
Assume 3 (pos 1) is smallest. Compare with position 2, 1 < 3, so assume position 2 has smallest value. Compare with position 3, 3 < 1. Since we are at the end switch smallest with first position. (position 1 and 2)
1,3,2
Now, since position 1 is done, start with position 2. Assume 3 (position 2) is the smallest value. Compare with position 3 (2). 2 < 3, so assume position 3 has smallest value. Since we are at the end of the array we switch position 2 and 3
1,2,3
Done
Your question appears to be in your comment
min = i;//Selection sort algorithm says that find the minimum in the
// array, but first element is not minimum.What's point here?
The point of that is you can assume the first one you're checking is the lowest just so you have a place to start from. After all, it might not be the minimum over all, but of the one's you've checked in this iteration, it's the lowest so far!
Selection sort is a sorting algorithm in which the smallest element is picked from an unsorted array and moved to the beginning of the array. In your case first find min value index from second for loop and swap outside on that loop.
private static void selectionSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int min = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min]) {
min = j;
}
}
if (min != i) {
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
}