Selection sort improves upon bubble sort as it minimizes number of swaps to O(n) as compared to bubble sort where number of swaps are in the order of O(n^2). We start from the leftmost element of an array and compute minimum of all elements which are right from current element then swap the current element with then minimum element. So at any point of time rightmost part from current element of the array is sorted. The worst case running time of this algorithm still remains same because finding minimum element in an array is O(n) so actual running time will be (n + n-1 + n-2 ... 1) = O(n^2)
10,9,11,5,2, start -> 0, min -> 2
2,9,11,5,10, start -> 1, min -> 5
2,5,11,9,10, start -> 2, min -> 9
2,5,9,11,10, start -> 3, min -> 10
2,5,9,10,11, start -> 4, min -> 11
Sorted Array -> 2,5,9,10,11
package com.thescalatutorial.examples object SelectionSort { def selectionSort(array: Array[Int]) = { def findMin(array: Array[Int], start: Int): Int = { var minIndex = start for (i <- start until array.size) { if (array(i) < array(minIndex)) { minIndex = i } } minIndex } def bubbleSortRecursive(array: Array[Int], start: Int): Array[Int] = { val minIndex = findMin(array, start) println(array.mkString(",") + ", start -> " + start + ", min -> " + array(minIndex)) start match { case _ if (start >= array.size - 1) => array case _ => var temp = array(start) array(start) = array(minIndex) array(minIndex) = temp bubbleSortRecursive(array, start + 1) } } bubbleSortRecursive(array, 0) } def main(args: Array[String]) { val sortedArray = selectionSort(Array(10, 9, 11, 5, 2)) println("Sorted Array -> " + sortedArray.mkString(",")) } }Running above program will produce following output:
10,9,11,5,2, start -> 0, min -> 2
2,9,11,5,10, start -> 1, min -> 5
2,5,11,9,10, start -> 2, min -> 9
2,5,9,11,10, start -> 3, min -> 10
2,5,9,10,11, start -> 4, min -> 11
Sorted Array -> 2,5,9,10,11
No comments:
Post a Comment