From 18418746933c46965242462a23c744c4e18ee9df Mon Sep 17 00:00:00 2001 From: FlyDinosaur <3457552420@qq.com> Date: Fri, 22 Mar 2024 03:49:36 +0000 Subject: [PATCH] I9AM96add codes/FlyDinosaur/BubbleSort.java. Signed-off-by: FlyDinosaur <3457552420@qq.com> --- codes/FlyDinosaur/BubbleSort.java | 49 +++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 codes/FlyDinosaur/BubbleSort.java diff --git a/codes/FlyDinosaur/BubbleSort.java b/codes/FlyDinosaur/BubbleSort.java new file mode 100644 index 000000000..15b0d94ae --- /dev/null +++ b/codes/FlyDinosaur/BubbleSort.java @@ -0,0 +1,49 @@ +package top.flydinosaur.openAnolis.demo; + +import java.util.Scanner; + +public class DemoTest { + + public static int[] generateArray(){ + Scanner input = new Scanner(System.in); + System.out.print("请输入数组的元素个数:"); + int length = input.nextInt(); //数组的元素个数 + int arr[] = new int[length]; + for (int i = 0; i < length; i++) { + System.out.print("请输入数组第" + (i+1) + "个元素:"); + arr[i] = input.nextInt(); + } + System.out.println("数组生成完成"); + input.close(); + return arr; + } + + public static void printArray(int[] arr){ + for (int i = 0; i < arr.length; i++) { + System.out.print(arr[i] + " "); + } + System.out.println(); + } + + public static int[] sort(int[] arr){ + 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; + } + } + } + return arr; + } + public static void main(String[] args) { + int[] array = generateArray(); + System.out.println("原始数组为:"); + printArray(array); + int[] sortedArray = sort(array); + System.out.println("排序后的数组为:"); + printArray(sortedArray); + + } +} -- Gitee