Sort the numbers using If, Else and Loop.

This is very interesting. You need to sort the numbers, but not using the SORT functions. You can use the If, Else or Loop to do the functions.

See the solution:

import java.util.Scanner;

public class OrderNumbers {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the size of an Array");
        int num = in.nextInt();
        int [] numbers = new int[num];
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("Enter the number "+(i+1)+" : ");
            numbers[i] = in.nextInt();
        }
        sortNumbers(numbers);
    }
    static void sortNumbers(int[] numbers){
        for (int i = 0; i < numbers.length; i++) {
            int newValue;
            for (int j = 0; j < numbers.length; j++) {
                if (numbers[i] < numbers[j]) {
                    newValue = numbers[j];
                    numbers[j] = numbers[i];
                    numbers[i] = newValue;
                }
            }
        }

        for (int x = 0; x < numbers.length; x++) {
            System.out.println(numbers[x]);
        }
    }

}

You know, this is a bubble sort.

Comments

Popular posts from this blog

Flutter Bloc - Clean Architecture

What's new in android 14?

Dependencies vs Dev Dependencies in Flutter