Sunday, 7 August 2016

Bubble Sort (Java Program)


Bubble Sort: In this algorithm, we compare two consequent elements in the list from the beginning till the end. For example - A[1]  and A[2] are compared and if A[1]>A[2], we swap them. we do this for n-1 passes, where n is number of elements. At the end of 1st pass we set the last element that is the largest of all. In the 2nd pass we set the second last element and so on. Also with every pass the number of elements to be compared becomes one less than before.

Program:

import java.util.*;
public class BubbleSort {

    public static void main(String[] args) {
        Scanner obj=new Scanner(System.in);
        int n=obj.nextInt();
        int z=n;
        double arr[]=new double[n];
        for(int i=0;i<n;i++){
            arr[i]=obj.nextDouble();
        }
        double temp;
        for(int i=0;i<n-1;i++){
            for(int j=0;j<n-1;j++){
                if(arr[j]>arr[j+1]){
                 temp=arr[j];
                 arr[j]=arr[j+1];
                 arr[j+1]=temp;
                }
            }
            n--;
        }
        for(int i=0;i<z;i++)
            System.out.println(arr[i]);
    }
 
}

No comments:

Post a Comment