Ordered Array in Kotlin

A sorted array is an array data structure in which each element is sorted in numerical, alphabetical, or some other order, and placed at equally spaced addresses in computer memory.

It is typically used in computer science to implement static lookup tables to hold multiple values which have the same data type. Sorting a stack of baby unicorns of different ages is useful in organizing data in ordered form and recovering them rapidly.


class OrderedArray<T:Comparable<T>>(list:MutableList<T>){
    var items: MutableList<T>  = this.quicksort(list) as MutableList<T>
    /**
     * Use quicksort algorithm to order elements in array
     */
    fun quicksort(its:List<T>):List<T>{
        if (its.count() < 1) return  its
        val pivot = its[its.count()/2]
        val equal = its.filter { it == pivot }
        val less = its.filter { it < pivot }
        val greater = its.filter { it > pivot }
        return quicksort(less) + equal + quicksort(greater)
    }
    fun insert(element:T){
        val position = findElementPosition(element)
        this.items.add(position, element)
    }
    /**
     * Use binarySearch algorithm to find the position for the new element in array
     */
    fun findElementPosition(element:T):Int{
        var rangeStart = 0
        var rangeEnd = this.items.count()
        while (rangeStart < rangeEnd) {
            val midIndex = rangeStart + (rangeEnd - rangeStart)/2
            if (this.items[midIndex] == element) {
                return midIndex
            } else if (this.items[midIndex] < element){
                rangeStart = midIndex + 1
            } else {
                rangeEnd = midIndex
            }
        }
        return rangeStart
    }
    override fun toString():String = this.items.toString()
}

fun main(args: Array<String>) {
    println("\nOriginal list:")
    val names = listOf<String>("Tim", "Steve", "Zack", "Adam", "John", "Peter", "Clark") as MutableList<String>
    println(names)
    println("\nOrdered list:")
    val ordered =  OrderedArray<String>(names)
    println(ordered)
    val n1 = "Paul"
    println("\nAdding ${n1} to the list:")
    ordered.insert(n1)
    println(ordered)
    val n2 = "Demetrius"
    println("\nAdding ${n2} to the list:")
    ordered.insert(n2)
    println(ordered)
}			

aaaaaaaaaaaaa
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Selenium Online Training : Our next online training course for Selenium with Java starts from 17th December 2018.

You can attend first 3 classes for free, the total course fee is INR 10,000

The course time would be 8.00 PM(IST) for the first three classes

If you are interested to learn, then you can join the course by sending email to chercher.tech@gmail.com

or Register below


 
Join My Facebook Group
Join Group