ITPub博客

首页 > 应用开发 > > LINUX排序算法

LINUX排序算法

作者:田野 时间:2019-09-12 15:05:10 0 删除 编辑

@Test

public void bubbleSort() {

    int[] arr = { 3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48 };

    // 统计比较次数

    int count = 0;

    // 第一轮比较

    for (int i = 0; i < arr.length - 1; i++) {

        // 第二轮比较

        for (int j = 0; j < arr.length - 1 - i; j++) {

            if (arr[j] > arr[j + 1]) {

                // 交换位置

                int temp = arr[j];

                arr[j] = arr[j + 1];

                arr[j + 1] = temp;

            }

            count++;

        }

    }

    System.out.println(Arrays.toString(arr));

    System.out.println("一共比较了:" + count + "次");

}

@Test

public void bubbleSort() {

    int[] arr = { 3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48 };

    // 统计比较次数

    int count = 0;

    for (int i = 0; i < arr.length - 1; i++) {

        boolean flag = true;

        for (int j = 0; j < arr.length - 1 - i; j++) {

            if (arr[j] > arr[j + 1]) {

                // 交换位置

                int temp = arr[j];

                arr[j] = arr[j + 1];

                arr[j + 1] = temp;

                flag = false;

            }

            count++;

        }

        if(flag) {

            break;

        }

    }

    System.out.println(Arrays.toString(arr));

    System.out.println("一共比较了:" + count + "次");

}

@Test

public void SelectionSort() {

    int[] arr = { 3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48 };

    for (int i = 0; i < arr.length - 1; i++) {

        int index = i;

        for (int j = 1 + i; j < arr.length; j++) {

            if (arr[j] < arr[index]) {

                index = j;// 保存最小元素的下标

            }

        }

        // 此时已经找到最小元素的下标

        // 将最小元素与前面的元素交换

        int temp = arr[index];

        arr[index] = arr[i];

        arr[i] = temp;

    }

    System.out.println(Arrays.toString(arr));

}

@Test

public void InsertionSort() {

    int[] arr = { 3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48 };

    for (int i = 1; i < arr.length; i++) {

        // 定义待插入的数

        int insertValue = arr[i];

        // 找到待插入数的前一个数的下标

        int insertIndex = i - 1;

        while (insertIndex >= 0 && insertValue < arr[insertIndex]) {

            arr[insertIndex + 1] = arr[insertIndex];

            insertIndex--;

        }

        arr[insertIndex + 1] = insertValue;

    }

    System.out.println(Arrays.toString(arr));

}

————————————————

版权声明:本文为CSDN博主「#Temptation」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/qq_42453117/article/details/99680831

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3522/viewspace-3131636/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-07-09

  • 博文量
    80
  • 访问量
    759