kotlin键值对数组_Kotlin程序以降序对数组进行排序

kotlin键值对数组

Given an array, we have to sort its elements in descending order.

给定一个数组,我们必须按降序对其元素进行排序。

Example:

例:

    Input:
    arr = [10, 20, 5, 2, 30]

    Output:
    sorted array (Descending Order): [30, 20, 10, 5, 2]

在Kotlin中按降序对数组进行排序的程序 (Program to sort an array in descending order in Kotlin)

package com.includehelp.basic

import java.util.*

//Main Function entry Point of Program
fun main(args: Array<String>) {
    //Input Stream
    val s = Scanner(System.`in`)

    //Input Array Size
    print("Enter number of elements in the array: ")
    val size = s.nextInt()

    //Create Integer array of Given size
    val intArray = IntArray(size)

    //Input array elements
    println("Enter Arrays Elements:")
    for (i in intArray.indices) {
        print("intArray[$i] : ")
        intArray[i] = s.nextInt()
    }

    //to Perform Descending Order Sorting on integer Array
    var temp:Int
    for (i in intArray.indices) {
        for (j in i + 1 until intArray.size) {
            if (intArray[i] < intArray[j]) {
                temp = intArray[i]
                intArray[i] = intArray[j]
                intArray[j] = temp
            }
        }
    }

    //Alternatively we can also use sortDescending() method 
    //of Arrays Class in kotlin to sort in Descending Order
    //intArray.sortDescending()

    print("Descending Order: ")
    for (item in intArray) {
        print("$item ")
    }
}

Output

输出量

Run 1:
-----
Enter number of elements in the array: 8
Enter Arrays Elements:
intArray[0] : 34
intArray[1] : 6
intArray[2] : -98
intArray[3] : 0
intArray[4] : 12
intArray[5] : 7
intArray[6] : 7
intArray[7] : 45
Descending Order: 45 34 12 7 7 6 0 -98
----------------
Enter number of elements in the array: 7
Enter Arrays Elements:
intArray[0] : 12
intArray[1] : 34
intArray[2] : 56
intArray[3] : 78
intArray[4] : 90
intArray[5] : -65
intArray[6] : 032
Descending Order: 90 78 56 34 32 12 -65


翻译自: https://www.includehelp.com/kotlin/sort-an-array-in-descending-order.aspx

kotlin键值对数组

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值