Selection 1
Selection 1
Sort
CONNECTING
Learning Intention
• Sorting is a process in which the elements of an
array are arranged in either ascending or descending
order.
✓Predict the status of the array during or after the sorting process
INTRODUCTION
• Selection sort is a combination of searching
and sorting.
The number of times the sort passes through the array is one
less than the number of items in the array.
For the first position in the sorted list, the whole list is scanned sequentially. The first position
where 14 is stored presently, we search the whole list and find that 10 is the lowest value. So we
replace 14 with 10. After one iteration. 10, which happens to be the minimum value in the list,
appears in the first position of the sorted list.
For the second position, where 33 is residing, we start scanning the rest of the list in a
linear manner. We find that 14 is the second lowest value in the list and it should
appear at the second place. We swap these values.
After two iterations, two least values are positioned at the beginning in a sorted
manner.
The same process is applied to the rest of the items in the array.
Selection Sort Technique
Original unsorted array
Pass 1
Pass 2
Pass 3
Pass 4
Pass 5
Pass 6
Pass 7
Pass 8
Selection Sort code
class selection_sort {
public static void main( ) {
int [] a={4,2,3,7,1,6};
int min, temp;
for ( int i = 0; i <a.length-1; i++ ) {
min = i; //initialize min with i assuming it contains the smallest value
for(int j = i+1; j < a.length; j++) //locate smallest element between positions i+1 to a.length
{
if( a[j] < a[min] )
min = j;// element at index j has the smaller value. Hence store it in min
} //for loop
if(i!=min) {
temp = a[min]; //swap smallest found in position min with element in position i
a[min] = a[ i ];
a[ i ] = temp;
}
}
// displaying elements
for( int i=0;i<a.length;i++)
System.out.println(a[i]);
}
}
END