Welcome to BigData School that can get you hired on Small startups or big Product based companies.Are you tired of 30-40 hours of theoritical bigdata courses in the market. Welcome to 240+ hours of Bigdata training. Just subscribe to our popup to get access to our 80+hours of course absolutely free.Try them out and you can join our further course once you are happy with our Demos.

Selection Sort

Big Data    On Thursday 22nd of June 2017 12:10:06 PM By Suraz Ghimire
Logic to implement selection sort.
Assume you have 5 element in an array.
Find the minimum number in array from 0 to 4. The minimum number should be assigned to arr(0)
Then find the minum number in array from 1 to 4. The minimum number should be assigned to arr(1)
Like wise, in each iteration we should get the minium element and that should be assigned to the beginning index of iteration.

assume the array is arr[]= {25,15,30,5,10,20} 
output should be {5,10,15,20,25,30}

Time complexity: O(n2) As we have nested loop.
Space complexity: O(1) 

Code in Scala
package sorting.sorting

object SelectionSort {

def sort(arr: Array[Int]): Unit = {

for(i<- 0 until arr.length){
var pos=i
for(j<-i+1 until arr.length){
if(arr(pos)>arr(j)){
pos=j
}

}
val temp=arr(pos)
arr(pos)=arr(i)
arr(i)=temp
}
}

def main(args: Array[String]): Unit = {
val arr=Array(25,15,30,5,10,20 )
sort(arr)
arr.foreach(println)

}
}

Output:
5
10
15
20
25
30

About Author

Suraz Ghimire