Working style of Selection sort
Selection sort is loop over the array till n records and select smallest no and move it to left one by one to.
Thus,
50,12,3,4,6
3,12,50,4,6
3,4,50,12,6
3,4,6,12,50
Otherwise move big numbers to right hand side one by one.
|
Selection sort example in JAVA
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | public class SelectionSort {
public static void display( int numbers[]){
for ( int i= 0 ;i<numbers.length;i++){
System.out.print(numbers[i]+ "\t" );
}
System.out.println();
}
public static void main(String args[]) throws Exception{
int numbers[] = { 48 , 34 , 5 , 12 , 8 };
for ( int i= 0 ;i<numbers.length;i++){
int small_no_index = i;
for ( int j=i+ 1 ;j<numbers.length;j++){
if (numbers[small_no_index] > numbers[j]){
small_no_index = j;
}
}
int tmp = numbers[i];
numbers[i] = numbers[small_no_index];
numbers[small_no_index] = tmp;
}
display(numbers);
}
}
|
|