arranging numbers in ascending order [closed]

This is quite basic program called selection sort.

The wiki article is: Selection sort.

Basically in this program, i is first pointing to the first element in the array. Then, j points to the next element. If, the element j is smaller than element i, they get swapped. After swapping, the inner for loop still continues, and then j points to the next element of what it was pointing to, and again it check if it is smaller, and swaps if it is true.

I think that is being a bit confusing, so I’ll now do it with a example.

Let’s say we have an array with 3 elements: 4 1 3. i points to the first element that is 4. j points to the second element that is 1. It checks if the element j is smaller than element i. Yes it is, so it swaps them. Now the array is: 143. Then j moves to the next element. It checks if element j is smaller than element i. No. Then, the inner loop finishes. Now, i is pointing to 4 and j is pointing to 3. It check if element j is smaller than element i. Yes, so it swaps them. So now the array is 134. well it continues the process till i is smaller than 3, or the number of elements of the array. Thus, now, the array got sorted in ascending order.

enter image description here

This image has been taken from the link mentioned earlier. Red is current min. Yellow is sorted list. Blue is current item.

Well, the line

a = number [i];

is just copying the value of element i of the array number to the variable a.

The line

number [i] = number [j];

is just copying the value of element j of the number array in its element i.

The line

number [j] = a;

is copying the value of a into the element j of the array number.

Basically, the lines

a = number [i];
number[i] = number [j];
number [j] = a;

are swapping the values of number [i] and number [j].

Leave a Comment