Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3651283
  • 博文数量: 880
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 6155
  • 用 户 组: 普通用户
  • 注册时间: 2016-11-11 09:12
个人简介

To be a better coder

文章分类

全部博文(880)

文章存档

2022年(5)

2021年(60)

2020年(175)

2019年(207)

2018年(210)

2017年(142)

2016年(81)

分类: LINUX

2019-09-10 09:52:03

https://blog.csdn.net/qq_42453117/article/details/99680831?utm_source=app


@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

阅读(556) | 评论(0) | 转发(0) |
0

上一篇:onos命令提示符操作

下一篇:时间复杂度

给主人留下些什么吧!~~