Pigeonhole Sort in Kotlin

Pigeonhole sorting is a sorting algorithm that is suitable for sorting lists of elements where the number of elements and the number of possible key values are approximately the same

Pigeonhole sorting is a sorting algorithm that is suitable for sorting lists of elements where the number of elements and the number of possible key values are approximately the same.

It requires O(n + Range) time where n is number of elements in input array and ‘Range’ is number of possible values in array.

It is similar to counting sort, but differs in that it moves items twice: once to the bucket array and again to the final destination

Shell Sort

Working of Algorithm :

  • Find minimum and maximum values in array. Let the minimum and maximum values be ‘min’ and ‘max’ respectively. Also find range as ‘max-min-1’.
  • Set up an array of initially empty “pigeonholes? the same size as of the range.
  • Visit each element of the array and then put each element in its pigeonhole. An element arr[i] is put in hole at index arr[i] – min.
  • Start the loop all over the pigeonhole array in order and put the elements from non- empty holes back into the original array.

Bubble Sort Complete code for Pigeonhole sort in kotlin


import java.util.Arrays

fun pigeonhole_sort(arr: IntArray, n: Int):IntArray {
    var min = arr[0]
    var max = arr[0]
    val range: Int
    var i: Int
    var j: Int
    var index: Int

    for (a in 0 until n) {
        if (arr[a] > max)
            max = arr[a]
        if (arr[a] < min)
            min = arr[a]
    }

    range = max - min + 1
    val phole = IntArray(range)
    Arrays.fill(phole, 0)

    i = 0
    while (i < n) {
        phole[arr[i] - min]++
        i++
    }


    index = 0

    j = 0
    while (j < range) {
        while (phole[j]-- > 0)
            arr[index++] = j + min
        j++
    }
    return arr

}

fun main(args: Array<String>) {
    val l = intArrayOf(-2, 0, -2, 5, 5, 3, -1, -3, 5, 5, 0, 2, -4, 4, 2)
    println(pigeonhole_sort(l, l.size).contentToString())
}

Output of the Pigeonhole sort in kotlin


[-4, -3, -2, -2, -1, 0, 0, 2, 2, 3, 4, 5, 5, 5, 5]	

Cocktail Sort

About Author

This article is written by Pavan, who is serving notice period in an MNC, Bangalore. He thought, let the articles speak rather than his image. He is also the same person who created the reporter for Protractor Jasmine

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions