ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

Java Source Code in Sorting: How to Sort Numbers in Ascending Order

Updated on November 1, 2013

Get A Website Plus a Free Domain Name in Just 1 Hour!

Bring the new technology in your hands! Share your skills, improve and impress. Get Your Own Website and a Free Domain Name Here!

Java Program: Sort Numbers inside an array in an Ascending Order with a Sample Java Source Code

Sorting in Java is always there when you are learning java programming. Sorting numbers in ascending order shows on how ‘nested for loops’ work together. This program also uses array with a fix size. Rather than declaring a variable per entered number let just assign an array to hold a multiple of numbers. That way the program is much shorter and executes better. So, to sort numbers in Java we will have this following algorithm: If the 1st entered number in an array is greater than the 2nd, the program should swap the 2 numbers and let the smallest number comes first. Otherwise, the program would not do anything. Then the program would print the sorted numbers in the screen. See the Java Source code below.

package sort_numbers_in_ascending_order;

import java.util.Scanner;

public class Main {

    public static void main(String[] args)
      Scanner input = new Scanner(;

        System.out.print("Enter 6 Numbers to Sort: ");
        int num;
        int[] num_in_array = new int[6];

        for(int enter_num=0; enter_num<6; enter_num++)
            num_in_array[enter_num] = input.nextInt();
            for(int sort_num=0; sort_num<6; sort_num++)
                if(num_in_array[enter_num] < num_in_array[sort_num])
                    int swap = num_in_array[enter_num];
                    num_in_array[enter_num] = num_in_array[sort_num];
                    num_in_array[sort_num] = swap;

        System.out.println("The Sorted Numbers are: ");

        for(int print = 0; print<6; print++)
            System.out.print(num_in_array[print]+ " ");



Sample Output:


    0 of 8192 characters used
    Post Comment

    No comments yet.