Selection Sort: Brute Force approach to sorting with example in Groovy

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(
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)){
   for(j in (i+1)..(total-1)){
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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s