How to sort a random number array in java?


To sort an array in Java, you need to compare each element of the array to all the remaining elements and verify whether it is greater if so swap them.

One solution to do so you need to use two loops (nested) where the inner loop starts with i+1 (where i is the variable of outer loop) to avoid repetitions in comparison.

Example

 Live Demo

import java.util.Arrays;
import java.util.Scanner;

public class ArrayInOrder {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array that is to be created::");
      int size = sc.nextInt();
      int[] myArray = new int[size];
      System.out.println("Enter the elements of the array ::");
   
      for(int i = 0; i<size; i++) {
         myArray[i] = sc.nextInt();
      }

      for(int i = 0; i<size-1; i++) {
         for (int j = i+1; j<myArray.length; j++) {
            if(myArray[i] > myArray[j]) {
               int temp = myArray[i];
               myArray[i] = myArray[j];
               myArray[j] = temp;
            }
         }
      }
      System.out.println(Arrays.toString(myArray));
   }
}

Output

Enter the size of the array that is to be created ::
6
Enter the elements of the array ::
54
63
14
78
2
3
[2, 3, 14, 54, 63, 78]

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements