11 Dec 2017

write a program for Bubble Sort.

Bubble sort is the simplest sorting algorithm.it works by iterating the input array from the first element to last, comparing each pair of the elements and swapping them if needed. Bubble sort continues its iteration until no more swap are needed. The algorithm gets its name from the way smaller elements “bubble” To the top of the list.

Worst case complexity
O(n2)
Best case complexity (improved version)
O(n)
Average case complexity (Basic version)
O(n2)
Worst case space complexity
O(1) auxiliary




class
BubbleSort
{
          public static void main(String[] args)
          {
                   int array[]=new int[]{2, 5, 2, 8, 5, 6, 8, 8};
                   for(int i=0; i<array.length; i++)
                   {
                             for(int j=0; j<array.length-1; j++)
                             {
                                      if(array[j]>array[j+1])
                                      {
                                                int temp = array[j+1];
                                                array[j+1] = array[j];
                                                array[j] = temp;
                                      }
                             }
                   }
                   System.out.println("Sorted List is::");
                   for(int i=0; i<array.length; i++)
                   {
                             System.out.print(array[i]+" ");
                   }

          }
}

Output:

Sorted List is::

2 2 5 5 6 8 8 8