In Selection sort technique the list is scanned to find the smallest element and it is then exchanged with the first element, putting the smallest element in its final position i.e at the beginning. Then the list is scanned starting from the second element to find the smallest among the remaining n-1 elements and exchange it with the second element to put the second smallest element in its final position. In general in the ith pass the algorithm searches for the smallest number from the n-i elements and swaps it with the element in the ith position i.e Ai. The list is sorted after n-1 passes.

//Groovy code for Selection Sort
//Ascending Order
println "Enter the count of Numbers"
Scanner reader = new Scanner(System.in)
lst = new ArrayList()
total = reader.nextInt()
total.times{println "Enter the ${it+1} number";lst.add(reader.nextInt())}
println "The numbers entered in sorted order are:"
for(i in 0..(total-2)){
min=i
for(j in (i+1)..(total-1)){
if(lst[min]>lst[j]){
temp=lst[min]
lst[min]=lst[j]
lst[j]=temp
}
}
}
lst.each{println "$it"}

The above is the groovy code for performing Selection Sort. The basic operation in this algorithm is the comparision lst[min]>lst[j] and this is executed each time during the running of the loop. Using the given data we can obtain that the number of times the operation is executed is n(n-1)/2. Thus, selection sort is of order n2.

### Like this:

Like Loading...

*Related*