Wednesday, December 4, 2024
HomeAlgorithmsSelection Sort Kotlin with Example - Sorting Algorithms #1

Selection Sort Kotlin with Example – Sorting Algorithms #1

-

Selection Sort is one of the most important sorting algorithm frequently looked upon and is even asked in the Interviews. In this article we will look at Selection Sort Kotlin Implementation with example.

Before diving into the code, let us see what is a Selection sort and Whether its efficient to use or not.

What is a Selection Sort

Selection sort is one of the simplest form of sorting. Its goal is simple: to find the smallest element and bring it to front. Then find the second smallest and move it to second position from front and so on.This will continue until all the elements are in position.

Since the algorithm repeatedly selects the smallest element, it is called as selection sort.

Related Links

Advantages

  • Easy,
  • No additional space required

Selection Sort Kotlin Algorithm Implementation:


fun main(args: Array<String>) {
val list = ArrayList(readLine()!!.split(" ").map { it.toInt() })
selection(list)
for(i in list) println(i)
}
fun selection(a: ArrayList<Int>) {
var min:Int
for (i in 0 until a.size) {
min = i
for (j in (i + 1) until a.size) {
if (a[j] < a[min]) {
min = j
}
}
swap(a, min, i)
}
}
fun swap(a : ArrayList<Int>, b: Int, c:Int) {
val temp = a[b]
a[b] = a[c]
a[c] = temp
}

Is it Efficient?

As you can see, in the above example, it consists of two for loops – one in line 9 and other in line 11 in the above example. So we know that the its Average and worst case Complexity is O(n2). Hence its inefficient compared to other algorithms.

In the next article we will be looking into few other important sorting techniques like bubble sort, merge sort etc.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

LATEST POSTS

Single Number | Leetcode 136 | 100 Days of Code Day 9

Welcome to Day 9 of Coderefer's 100 Days of code where we will be solving problems from Coderefer DSA sheet each day and today we...

3 Sum | Leetcode #15 | 100 Days of Code Day 10

Today we are going to solve 3 Sum - our first Medium Level Array problem from Coderefer DSA Sheet. If you are new to this...

Best Time to Buy and Sell Stock – Day 7 | 100 Days of Code

Welcome to Day 7 of 100 Days of Code where today we solve yet another most frequently asked easy array problem called - Best Time...

Contains Duplicate – Day 8 | 100 Days of Code

Welcome to Day 8 of 100 Days of Code and today we are going to solve yet another easy-level problem - Contains Duplicate as part...

Follow us

1,358FansLike
10FollowersFollow
398SubscribersSubscribe

Most Popular