Sorting Arrays
Sorting is a process of arranging the values of array in a particular order. An array can be sorted in two orders:
Ascending Sort
In ascending order, the smallest value is stored in the first element of array; second smallest value is stored in the second element and so on. The largest value is stored in the last element. Following figure shows an array sorted in ascending order.
Sorted Array in Ascending order |
Descending Sort
In descending order, the largest value is stored in first element of array, second largest value is stored in second element and so on. The smallest value is stored in the last element.
The following figure shows an array sorted in descending order.
Sorted Array in Descending order |
Selection Sort
Selection sort is a technique that sorts an array. It selects an element in the array and moves it to its proper position. Selection sort works as follows:
- Find minimum value in the list.
- Swap it with the value in the first position.
- Sort the remainder of the list excluding the first value.
Working of Selection Sort
minimum
with the second element. If the second element is smaller than minimum
, assign the second element as minimum
.Compare
minimum
with the third element. Again, if the third element is smaller, then assign minimum
to the third element otherwise do nothing. The process goes on until the last element.minimum
is placed in the front of the unsorted list.swap the first with minimum |
The third iteration |
The fourth iteration |