budd/src/main/java/io/github/ehlxr/sort/BubbleSort.java

83 lines
3.2 KiB
Java
Raw Normal View History

2020-12-10 03:05:29 +00:00
/*
* The MIT License (MIT)
*
* Copyright © 2020 xrv <xrg@live.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
2020-12-09 09:55:24 +00:00
package io.github.ehlxr.sort;
2020-10-01 09:34:22 +00:00
import java.util.Arrays;
/**
*
* <p>
2020-11-08 14:23:36 +00:00
*
*
* <p>
*
2021-05-24 15:12:21 +00:00
* O(n²)
2020-10-01 09:34:22 +00:00
*
* @author ehlxr
* @since 2020-10-01 16:40.
*/
public class BubbleSort {
/**
*
* .
2020-11-08 14:23:36 +00:00
* .
2020-10-01 09:34:22 +00:00
* .
* . ~
*/
public static void sort(int[] arr) {
//外层:需要 length-1 次循环比较
for (int i = 0; i < arr.length - 1; i++) {
2021-05-28 14:48:00 +00:00
boolean flag = false;
2020-10-01 09:34:22 +00:00
//内层:每次循环需要两两比较的次数,每次比较后,都会将当前最大的数放到最后位置,所以每次比较次数递减一次
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
2021-05-28 14:48:00 +00:00
flag = true;
2020-10-01 09:34:22 +00:00
swap(arr, j, j + 1);
}
}
System.out.println("Sorting: " + Arrays.toString(arr));
2021-05-28 14:48:00 +00:00
if (!flag) {
break;
}
2020-10-01 09:34:22 +00:00
}
}
public static void swap(int[] arr, int i, int j) {
// arr[i] = arr[i] + arr[j];
// arr[j] = arr[i] - arr[j];
// arr[i] = arr[i] - arr[j];
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public static void main(String[] args) {
2021-05-28 14:48:00 +00:00
sort(new int[]{4, 9, 1, 6, 8, 10});
2020-10-01 09:34:22 +00:00
}
}