Tuesday, 22 December 2015

Java program to sort numbers in ascending order (Bubble Sort)

Requirement: I have an array of numbers { 23, 5, 33, 1, 7, 12, 3, 34, 0 }. I want to write a Java program that will sort the numbers in ascending order. Thus the output should be 34 33 23 12 7 5 3 1 0

Solution: The Java program for the above requirement is shown below:

Program 1:
package com.susanto;
public class SortingNumberAcs {

       public static void main(String[] args) {
             int numbers[] = { 23, 5, 33, 1, 7, 12, 3, 34, 0 };
             int temp = 0;
             for (int i = 0; i < numbers.length; i++) {
                    for (int j = 1; j < (numbers.length - i); j++) {
                           if (numbers[j - 1] < numbers[j]) {
                                 temp = numbers[j - 1];
                                 numbers[j - 1] = numbers[j];
                                 numbers[j] = temp;
                           }
                    }
             }
             for (int i = 0; i < numbers.length; i++) {
                    System.out.print(numbers[i] + " ");
             }
       }
}

Output:
34 33 23 12 7 5 3 1 0
Hence the solution to our requirement.


Thanks & Regards,
Susanto Paul