sort array in ascending order java code example

Example 1: sort array java

Here’s the java program to sort an array using Arrays.sort() method.

import java.util.Arrays;
public class JavaArraySortMethod
{
   public static void main(String[] args)
   {
      String[] strGiven = {"Great Barrier Reef", "Paris", "borabora", "Florence","tokyo", "Cusco"};
      Arrays.sort(strGiven);
      System.out.println("Output(case sensitive) : " + Arrays.toString(strGiven));
   }
}

Example 2: efficient way to sort an array in java

enum Code {
    Str1(1), Str2(2), Str3(3), Str4(4), Str5(5));

    int sortNumber;

    Code(int sortNumber) {
        this.sortNumber = sortNumber;
    }

    int returnNumber() {
        return sortNumber;
    }
};

public static void main(String[] args) {
    List<Object> obj = new ArrayList<Object>();

    Collections.sort(obj, new Comparator<Object>() {
        @Override
        public int compare(Object object1, Object object2) {
            return Code.valueOf(object1.getStr()).returnNumber() > Code.valueOf(object2.getStr()).returnNumber() ? 1 : -1;
        }
    });
}

Example 3: sorting array in ascending order java

import java.util.Arrays;
public class JavaArraySortMethod
{
   public static void main(String[] args)
   {
   String[] strGiven = {"Great Barrier Reef", "Paris", "borabora","tokyo", "Cusco"};
   Arrays.sort(strGiven);
   System.out.println("Output(case sensitive) : " + Arrays.toString(strGiven));
   }
}

Example 4: how to sort an array

import java.util.Scanner;
public class JavaExample 
{
    public static void main(String[] args) 
    {
    	int count, temp;
    	
    	//User inputs the array size
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter number of elements you want in the array: ");
        count = scan.nextInt();
    
        int num[] = new int[count];
        System.out.println("Enter array elements:");
        for (int i = 0; i < count; i++) 
        {
            num[i] = scan.nextInt();
        }
        scan.close();
        for (int i = 0; i < count; i++) 
        {
            for (int j = i + 1; j < count; j++) { 
                if (num[i] > num[j]) 
                {
                    temp = num[i];
                    num[i] = num[j];
                    num[j] = temp;
                }
            }
        }
        System.out.print("Array Elements in Ascending Order: ");
        for (int i = 0; i < count - 1; i++) 
        {
            System.out.print(num[i] + ", ");
        }
        System.out.print(num[count - 1]);
    }
}