java方面的问题,关于冒泡排序

2025-03-12 01:57:15
推荐回答(3个)
回答1:

你的冒泡排序的代码有问题。

public class Main {
    //定义冒泡排序方法,参数为数组a
    static void bubble_sort(int[] unsorted)
    {
        for (int i = 0; i < unsorted.length; i++)
        {
            for (int j = i; j < unsorted.length; j++)
            {
                if (unsorted[i] > unsorted[j])
                {
                    int temp = unsorted[i];
                    unsorted[i] = unsorted[j];
                    unsorted[j] = temp;
                }
            }
        }
    }

    public static void main(String[] args) {
        //定义一个int类型的数组
        int[] arr = {12, 54, 64, 53, 89, 34, 59, 34, 76, 23};
        //调用方法对数组进行排序
        bubble_sort(arr);
        //输出排序后的数组
        for (int i = 0; i < arr.length; i++){
            System.out.print(arr[i] + "\t");
        }
    }

}

回答2:

  public static void main(String[] args) {
   Scanner sc = new Scanner(System.in);
   int[] array = new int[5];
   System.out.println("请输入一个长度为5的整数数组------");
   for (int i = 1; i <= array.length; i++) {
   System.out.print("输入第" + i + "整数:");
   int sum = sc.nextInt();
   array[i - 1] = sum;
   }
   System.out.println("排序前:");
   for (int a : array) {
   System.out.print(a);
   System.out.print(" ");
   }
   bubble_sort(array);
   System.out.println();
   System.out.println("排序后:");
   for (int b : array) {
   System.out.print(b);
   System.out.print(" ");
   }

  }

  static void bubble_sort(int[] unsorted) {
   for (int i = 0; i < unsorted.length; i++) {
    for (int j = i; j < unsorted.length; j++) {
   if (unsorted[i] > unsorted[j]) {
    int temp = unsorted[i];
    unsorted[i] = unsorted[j];
   unsorted[j] = temp;
   }
   }
   }
  }

回答3:

你外循环小于数组长度ok了