Programming Blog

This blog is about technical and programming questions and there solutions. I also cover programs that were asked in various interviews, it will help you to crack the coding round of various interviews

Tuesday 26 December 2017

Java program to implement bubble sort

Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm, which is a comparison sort, is named for the way smaller or larger elements "bubble" to the top of the list. Although the algorithm is simple, it is too slow and impractical for most problems even when compared to insertion sort.Bubble sort can be practical if the input is in mostly sorted order with some out-of-order elements nearly in position.

                                   Procedure
procedure bubbleSort( A : list of sortable items )
    n = length(A)
    repeat
        swapped = false
        for i = 1 to n-1 inclusive do
            /* if this pair is out of order */
            if A[i-1] > A[i] then
                /* swap them and remember something changed */
                swap( A[i-1], A[i] )
                swapped = true
            end if
        end for
    until not swapped
end procedure 

                                  Program 
  
Import java.util.Scanner;
public class BSort
{    
static void Sort(int[] arr)
{        
int n = arr.length;
int temp = 0;         
for(int i=0; i < n; i++)
 {                 
  for(int j=1; j < (n-i); j++)
  {                        
   if(arr[j-1] > arr[j])
   {
    temp = arr[j-1];
    arr[j-1] = arr[j];
    arr[j] = temp;
   }                             
  }         
 }      
}    

public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter no of array elements");
int size =sc.nextInt();
int arr[]=new arr[size]; 
System.out.println("Enter array elements");
for(int s=0;s<size;s++)
arr[s]=sc.nextInt();
System.out.println("Before Sorting");               
for(int i=0; i < size; i++)
 {                     
  System.out.print(arr[i] + " ");                
 }
System.out.println();                                  
bubbleSort(arr);                                
System.out.println("After  Sorting");                
for(int i=0; i < size; i++)
 {                     
  System.out.print(arr[i] + " ");          
 }
}
 

No comments:

Post a Comment