diff --git a/codes/Shephatiah/18693174.java b/codes/Shephatiah/18693174.java new file mode 100644 index 0000000000000000000000000000000000000000..856d733ffb82ef11c664a2e2bafb7b50c197802e --- /dev/null +++ b/codes/Shephatiah/18693174.java @@ -0,0 +1,25 @@ +public class BubbleSort { + public static void bubbleSort(int[] arr) { + int n = arr.length; + // 一共进行n - 1轮排序 + for (int i = 0; i < n - 1; i++) { + // 每一轮比较的次数会逐渐减少 + for (int j = 0; j < n - 1 - i; j++) { + // 比较相邻元素,如果前面的大于后面的则交换 + if (arr[j] > arr[j + 1]) { + int temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + } + } + } + } + + public static void main(String[] args) { + int[] arr = {5, 4, 3, 2, 1}; + bubbleSort(arr); + for (int num : arr) { + System.out.print(num + " "); + } + } +}