Bubble Sort - Sorting Algorithms

No comments

In bubble sort we compare adjacent elements of the array and swap them to maintain the sorting order.
So if we are trying to sort the element in the ascending order then in each iteration the largest element is moved to the rightmost position of the unsorted part of the array.

Let’s try to understand bubble sort with the help of an example -
Suppose we want to sort an array in ascending order - {12, 11, 23, 1, 23, 65, 33, 25, 87, 57, 6 }
Compare 12 with 11 , since 11 < 12 - swap elements (11 with 12)

{11, 12, 23, 1, 23, 65, 33, 25, 87, 57, 6 }
Compare 12 with 23, since 12 < 23 - no swaping required

{11, 12, 23, 1, 23, 65, 33, 25, 87, 57, 6 }
Compare 23 with 1 , since 1 < 23, swap elements (1 with 23)

{11, 12, 1, 23, 23, 65, 33, 25, 87, 57, 6 }
...

This way after completing the first pass we will see that the largest element has been shifted to the rightmost position of the unsorted part of the array.

After first pass -
11 12 1 23 23 33 25 65 57 6 87

After 2nd pass -
11 1 12 23 23 25 33 57 6 65 87

After 3rd pass -
1 11 12 23 23 25 33 6 57 65 87

After n pass
1 6 11 12 23 23 25 33 57 65 87 - Sorted array

Let’s write a Java program for Bubble Sort :

package algo.sorting;


public class BubbleSort {

public static void main(String args[]) {
  int[] arr = new int[] { 12, 11, 23, 1, 23, 65, 33, 25, 87, 57, 6 };
  
  System.out.println("Unsorted Array - ");
  for (int i = 0; i < arr.length; i++) {
   System.out.print(arr[i] + " ");
  }
  
  arr = sort(arr);

  System.out.println();
  System.out.println("Sorted Array After Bubble Sort - ");
  for (int i = 0; i < arr.length; i++) {
   System.out.print(arr[i] + " ");
  }
 }

 public static int[] sort(int[] arr) {
  int n = arr.length;

  for (int i = 0; i < n; i++) {
   for (int j = 0; j < n - i - 1; j++) {
    if (arr[j + 1] < arr[j]) {
     int temp = arr[j];
     arr[j] = arr[j + 1];
     arr[j + 1] = temp;
    }
   }
  }
  return arr;
 }
}

Output -
Unsorted Array - 
12 11 23 1 23 65 33 25 87 57 6 
Sorted Array After Bubble Sort - 
1 6 11 12 23 23 25 33 57 65 87 

No comments :

Post a Comment