Advertisement
nachtvaohal

pyramid-sort-sift-up-approach

Feb 23rd, 2024
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.51 KB | None | 0 0
  1. fun <T : Any> Array<T>.pyramidSort(comparator: Comparator<T>) {
  2.     for (i in lastIndex downTo 1) {
  3.         heapForRange(0, i, comparator)
  4.         swap(0, i)
  5.     }
  6. }
  7.  
  8. private fun <T : Any> Array<T>.heapForRange(start: Int, end: Int, comparator: Comparator<T>) {
  9.     for (i in end downTo start) {
  10.         siftUp(i, comparator)
  11.     }
  12. }
  13.  
  14. private fun <T : Any> Array<T>.siftUp(index: Int, comparator: Comparator<T>) {
  15.     val parentIndex = if (index == 0) 0 else (index - 1) / 2
  16.     if (comparator.compare(this[parentIndex], this[index]) < 0) {
  17.         swap(parentIndex, index)
  18.         siftUp(parentIndex, comparator)
  19.     }
  20. }
  21.  
  22. private fun <T: Any> Array<T>.swap(left: Int, right: Int) {
  23.     val temp = this[right]
  24.     this[right] = this[left]
  25.     this[left] = temp
  26. }
  27.  
  28. /**
  29.  * Представление стажёра.
  30.  */
  31. data class Intern (
  32.     val name: String,
  33.     val taskCount: Int,
  34.     val penalty: Int
  35. )
  36.  
  37. fun main() {
  38.     val reader = System.`in`.bufferedReader()
  39.     val writer = System.out.bufferedWriter()
  40.     val count = reader.readLine().toInt()
  41.  
  42.     val comparator = compareByDescending<Intern> { it.taskCount }
  43.         .thenBy { it.penalty }
  44.         .thenBy { it.name }
  45.  
  46.     val array = Array(count) {
  47.         val (name, taskCount, penalty) = reader.readLine().split(" ")
  48.         Intern(name, taskCount.toInt(), penalty.toInt())
  49.     }
  50.     array.pyramidSort(comparator)
  51.  
  52.     with(writer) {
  53.         array.forEach {
  54.             println(it.name)
  55.         }
  56.         flush()
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement