Sorting

Sorting is nothing but arranging the elements in particular order either ascending or descending order. Here, the Bubble sort is used in that the two adjacent elements are compared with each other. If the first number is greater than second number then we swap these two numbers otherwise no swapping of numbers. We use two loops one for 'pass' and other to check for the exchange. In program we read 10 numbers from keyboard and store them in an array. 

We have also use here for-each version of 'for' loop. The general form of for-each loop is given below:
for(data_type variable : array | collection)
{

}

PROGRAM
import java.util.Scanner;

class Sorting {

  static int arr[] = new int[10];
  
  public static void main(String[] args) {
    
    int temp;
    Scanner s = new Scanner(System.in);
    
    System.out.println("Enter 10 elements...");
    
    for(int i=0; i<10; i++) {
      
      arr[i] = s.nextInt();
    }
    
    System.out.println("Before sorting elements are..");
    displayElements();
    
    for(int i=0;i<10-1;i++) {   //  Loop for passes
      
      for(int j=0;j<(10-i-1);j++) {  //  Loop to sort element
      
        if(arr[j] > arr[j+1]) { //  Checking for less element
        
          /*  Exchange greater element with smaller element */
          temp = arr[j];
          arr[j] = arr[j+1];
          arr[j+1] = temp;
        }
      }
    }

    
    System.out.println("\n\nAfter sorting elements are..");
    displayElements();
  }

  private static void displayElements() {
    
    for(int a : arr) { // for-each loop
      
      System.out.print(a + " ");
    }
  }
}
OUTPUT
C:\>javac Sorting.java
C:\>java Sorting
Enter 10 elements...
12
56
23
45
85
64
51
47
11
95
Before sorting elements are..
12 56 23 45 85 64 51 47 11 95 

After sorting elements are..
11 12 23 45 47 51 56 64 85 95 

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative