Java kotlin 冒泡排序复习

2022-12-06  本文已影响0人  Luke_单车
1. Java 冒泡排序

冒泡排序 通过对排序序列从前向后(从下标较小的元素开始)依次比较相邻元素的值,若发现逆序则交换,使得值比较大的元素逐渐从前向后移动,就像水底下的气泡一样逐渐向上冒。

    public static void main(String[] args) {
        int[] arrayInt = {10, 33, 1, 0, 98, 4, 8, 2, 77, 21, 55, 12, 14, 54};
        for (int i = 0; i < arrayInt.length - 1; i++) {
            for (int j = 0; j < arrayInt.length - i; j++) {
                if (arrayInt[j] > arrayInt[j + 1]) {
                    int temp = arrayInt[j];
                    arrayInt[j] = arrayInt[j + 1];
                    arrayInt[j + 1] = temp;
                }
            }
        }
        for (int value : arrayInt) {
            System.out.println(value + "\t");
        }
    }
2. kotlin 冒泡排序
fun main() {
    fun swap(list: ArrayList<Int>, index1: Int, index2: Int) {
        val maxIndex = list.size - 1
        val minIndex = 0
        if (index1 < minIndex || index1 > maxIndex) throw IndexOutOfBoundsException()
        if (index2 < minIndex || index2 > maxIndex) throw IndexOutOfBoundsException()
        val tmp = list[index1]
        list[index1] = list[index2]
        list[index2] = tmp
    }

    fun bubbleSort(list: ArrayList<Int>) {
        if (list.size == 0) return
        val maxIndex = list.size - 1
        // 标识算法执行过程中是否发生过交换操作
        var haveSwap = false
        for (n in 0 until maxIndex) {
            for (i in 0 until maxIndex - n) {
                if (list[i] > list[i + 1]) {
                    swap(list, i, i + 1)
                    haveSwap = true
                }
            }
            if (!haveSwap) return
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读