Bubble Sort Program in Java

What is Bubble Sort?

Bubble sort is a simple algorithm which compares the first element of the array to the next one. If the current element of the array is numerically greater than the next one, the elements are swapped. Likewise, the algorithm will traverse the entire element of the array.
In this tutorial, we will create a JAVA program to implement Bubble Sort. Check the output of the code that will help you understand the program logic
  1. package com.guru99;
  2. public class BubbleSort {
  3. public static void main(String[] args)
  4. {
  5. int arr[] ={860,8,200,9};
  6. System.out.println("---Array BEFORE Bubble Sort---");
  7. printArray(arr);
  8. bubbleSort(arr);//sorting array elements using bubble sort
  9. System.out.println("---Array AFTER Bubble Sort---");
  10. printArray(arr);
  11. }
  12. static void bubbleSort(int[] array)
  13. {
  14. int n = array.length;
  15. int temp = 0;
  16. for(int i=0; i < n; i++) // Looping through the array length
  17. { System.out.println("Sort Pass Number "+(i+1));
  18. for(int j=1; j < (n-i); j++)
  19. {
  20. System.out.println("Comparing "+ array[j-1]+ " and " + array[j]);
  21. if(array[j-1] > array[j])
  22. {
  23. //swap elements
  24. temp = array[j-1];
  25. array[j-1] = array[j];
  26. array[j] = temp;
  27. System.out.println(array[j] + " is greater than " + array[j-1]);
  28. System.out.println("Swapping Elements: New Array After Swap");
  29. printArray(array);
  30. }
  31. }
  32. }
  33. }
  34. static void printArray(int[] array){
  35. for(int i=0; i < array.length; i++)
  36. {
  37. System.out.print(array[i] + " ");
  38. }
  39. System.out.println();
  40. }
  41. }

Output:

860 8 200 9 
Sort Pass Number 1
Comparing 860 and 8
860 is greater than 8
Swapping Elements: New Array After Swap
8 860 200 9 
Comparing 860 and 200
860 is greater than 200
Swapping Elements: New Array After Swap
8 200 860 9 
Comparing 860 and 9
860 is greater than 9
Swapping Elements: New Array After Swap
8 200 9 860 
Sort Pass Number 2
Comparing 8 and 200
Comparing 200 and 9
200 is greater than 9
Swapping Elements: New Array After Swap
8 9 200 860 
Sort Pass Number 3
Comparing 8 and 9
Sort Pass Number 4
---Array AFTER Bubble Sort---
8 9 200 860 

No comments:

Post a Comment