on Leave a Comment

Java Program for Bubble Sort

This java program sorts an array using bubble sort technique. In bubble sort technique, adjacent elements of array are compared. If the current element is greater than next element, then both elements perform swapping.

Java Program for Bubble Sort

import java.util.Scanner;

class BubbleSort
{
    public static void main(String [] args)
    {
        int n, i, j, swap;
        Scanner index = new Scanner(System.in);
        System.out.print("Enter length of integer array : ");
        n = index.nextInt();
        int array[] = new int[n];
        System.out.print("Enter elements of array : ");
        for (i = 0; i < n; i++) 
           array[i] = index.nextInt();
         for(i=0; i < n; i++){  
            for(j=1; j < (n-i); j++){  
              if(array[j-1] > array[j]){  
                swap = array[j-1];  
                array[j-1] = array[j];  
                array[j] = swap;  
               }        
            }  
         }  
        System.out.println("Sorted list of numbers");
        for (i = 0; i < n; i++) 
           System.out.print(array[i]+"  ");
    }
}

Output:

Enter length of integer array : 5
Enter elements of array : 4 9 6 3 1
Sorted list of numbers
1  3  4  6  9

0 comments:

Post a Comment