Search code examples
javaarraysnumerical

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


I would like to sort my two arrays in numerical order. So if I input something like: 96 2 1 42 49 5, it'll give me an output of: 1 2 42 49 96.

How would you do this using a for-loop? I'm trying to implement a basic for-loop to get my numbers to ascend numerically.

Here's the code:

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();

  }
}

Solution

  • Using Bubble Sort. You will be required to use 2 for loops.

    Complexity of bubble sort is 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]);
        }
    }
    

    output

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