Saturday, August 29, 2020

Bubble Sort

Note:- In Bubble sort, elements are swap n*(n-1) times.

package dataStructure;

class BubbleSort {
 public static void main(String[] args) {
  int data[] = { 4, -5, 2, 6, 1 };
  System.out.print("Input data for Sorting : ");
  printArray(data);
  BubbleSort(data);
 }

 static void BubbleSort(int[] array) {
  int n, c, d;
  n = array.length;
  for (c = 0; c < (n - 1); c++) {
   for (d = 0; d < n - c - 1; d++) {
    if (array[d] > array[d + 1]) /* For descending order use < */
    {
     // swap elements
     swap(d, array);
    }
    printArray(array);
   }
  }

  System.out.print("Output - Sorted data:");
  printArray(array);
 }

 static void swap(int num, int[] array) {
  int swap = array[num];
  array[num] = array[num + 1];
  array[num + 1] = swap;
 }

 static void printArray(int[] array) {
  for (int i = 0; i < array.length; i++) {
   System.out.print(array[i] + " ");
  }
  System.out.println();

 }
}

Output:
Input data for Sorting : 4 -5 2 6 1 
-5 4 2 6 1 
-5 2 4 6 1 
-5 2 4 6 1 
-5 2 4 1 6 
-5 2 4 1 6 
-5 2 4 1 6 
-5 2 1 4 6 
-5 2 1 4 6 
-5 1 2 4 6 
-5 1 2 4 6 
Output - Sorted data:-5 1 2 4 6 

No comments:

Post a Comment