Introduction
Selection sort is the simplest sorting algorithm in terms of implementation.Let's consider we have a list of elements i.e. {3, 9, 0, 5, 4 }
a) Selection sort maintains two sublists, one sorted and initially empty and second unsorted sublist i.e.
[ {}, {3, 9 , 0, 5 ,4 }]
b) It searches for the minimum element (for ascending sort) OR for a maximum element( for descending sort) in the unsorted list in each step.
Step 1
[ {0 }, {9,3,5,4}]Minimum element = 0 , swapped with 3
Step 2
Minimum element = 3 , swapped with 9[{0,3) , {9,5,4} ]
Step 3
Minimum element = 4 , swapped with 9[{0,3,4} , {5,9}]
Step 4
Minimum element = 5 , swapped with itself[{0,3,4,5}, {9}]
Step 5
Minimum element = 9 , swapped with itself[{0,3,4,5,9}, {}]
Worst Complexity: O(n*n)
Best Complexity : O(n * n)
Implementation
package main.scala
object SelectionSort {
val array = Array(0, 5, 2, 6, 3, 1)
def main(args: Array[String]) {
print("Unsorted List ")
println(array.toList)
print("Asceding sorted List ")
sortAscending;
println(array.toList)
sortDescending
print("Desceding sorted List ")
println(array.toList)
}
def sortAscending {
for (outer <- 0 until array.length) {
var minimumIndex = outer;
for (inner <- outer + 1 until array.length) {
if (array.apply(minimumIndex) > array.apply(inner)) {
minimumIndex = inner
}
}
swap(minimumIndex, outer)
}
}
def sortDescending {
for (outer <- 0 until array.length) {
var maximumIndex = outer;
for (inner <- outer + 1 until array.length) {
if (array.apply(maximumIndex) < array.apply(inner)) {
maximumIndex = inner
}
}
swap(maximumIndex, outer)
}
}
def swap(minimumIndex: Int, swapIndex: Int) {
var temp = array.apply(minimumIndex)
array.update(minimumIndex, array.apply(swapIndex))
array.update(swapIndex, temp)
}
}
Input : 3,9, 0, 5 ,4
Output: 0 3 4 5 9 (Ascending)
Output: 9 5 4 3 0 (Descending)
Output: 0 3 4 5 9 (Ascending)
Output: 9 5 4 3 0 (Descending)
Conclusion
In this tutorial, we learned how to implement Selection Sort using Scala language. Please leave your comments in the comment box. Happy learning :)
Comments
Post a Comment