按数字顺序排列的数组(不导入 array.sort() 选项)

Arrays in numerical order (without importing array.sort() option)

我想按数字顺序对我的两个数组进行排序。所以如果我输入类似:96 2 1 42 49 5,它会给我一个输出:1 2 42 49 96.

您将如何使用 for 循环执行此操作?我正在尝试实现一个基本的 for 循环来让我的数字在数字上上升。

代码如下:

public static void main(String[] args) {

    System.out.println("Input up to '10' numbers for current array: ");

    int[] array1 = new int[10];
    int i;
    int k;
    Scanner scan = new Scanner(System.in);

    for (i = 0; i < 10; i++) {
        System.out.println("Input a number for " + (i + 1) + ": ");
        int input = scan.nextInt();
        if (input == -9000) {
            break;
        } else {
            array1[i] = input;
        }
    }

    System.out.println("\n" + "Array 1: ");

    for (int j = 0; j < i; j++) {

        System.out.println((j + 1) + ": " + array1[j]);
    }

    int[] array2 = new int[i];

    System.out.println("\n" + "Array 2: ");

    for (int j = 0; j < i; j++) {
        array2[j] = array1[j];

        System.out.println((j + 1) + ": " + array2[j]);
    }
    scan.close();

  }
}

有很多sorting algorithms that can address this task. Each algorithm makes a trade-offs between speed and complexity. The simplest sorting algorithm is the bubble sort。冒泡排序效率低下,但如果您处理的是小型数组,则使用起来完全合理。

使用冒泡排序。您将需要使用 2 个 for 循环。

冒泡排序的复杂度O(n2)

package com.*;

import java.util.Scanner;

public class Sort {

    public static void main(String[] args) {
        int n, c, d, swap;
        Scanner in = new Scanner(System.in);

        System.out.println("Input number of integers to sort");
        n = in.nextInt();

        int array[] = new int[n];

        System.out.println("Enter " + n + " integers");

        for (c = 0 ; c < n ; c++)
            array[c] = in.nextInt();

        for (c = 0 ; c < (n - 1) ; c++) {
            for (d = 0 ; d < n - c - 1 ; d++) {
                if (array[d] > array[d + 1]) /* For descending order use < */
                {
                    swap = array[d];
                    array[d] = array[d + 1];
                    array[d + 1] = swap;
                }
            }
        }

        System.out.println("Sorted list of numbers");

        for (c = 0 ; c < n ; c++)
            System.out.println(array[c]);
    }
}

输出

Input number of integers to sort
5
Enter 5 integers
96
2
1
42
49
Sorted list of numbers
1
2
42
49
96