I have problem understanding the selection sort algorithm where integers are rearranged from lowest to highest value. Here is the code:
#include<iostream>
using namespace std;
void SelectionSort(int A[], int n)
{
for (int i = 0; i < n-1; i++)
{
int iMin = i;
for (int j = i+1; j < n; j++)
{
if (A[j] < A[iMin])
iMin = j;
}
int temp = A[i];
A[i] = A[iMin];
A[iMin] = temp;
}
}
int main()
{
int A[] = {2, 4, 3, 5, 1};
SelectionSort(A, 5);
for (int i = 0; i < 5; i++)
cout<<A[i]<<" ";
}
Can someone help me by explaining in details how the integers are rearranged and give some comments to each line? Maybe its easy but I am dumb in programming. :(
In coding writing comments in each line doesn't usually make sense, because the line itself usually states very clearly what it does. What matters though is the structure.
What your algorithm does is go trough the list from beginning to end (the first for
), and for each integer in the list, it swaps the current integer with the smallest integer in the rest of the list.
But to do this, it needs to find it first. This is where the second for
comes in. It walks trough the rest of the list (because it starts at i
and not at 0
), and remembers the position (iMin
) of the smallest integer.