Skip to content

Instantly share code, notes, and snippets.

@AnAverageBeing
Created October 14, 2022 17:12
Show Gist options
  • Save AnAverageBeing/f2387fa7c70c86dfecfc738ae5d7c710 to your computer and use it in GitHub Desktop.
Save AnAverageBeing/f2387fa7c70c86dfecfc738ae5d7c710 to your computer and use it in GitHub Desktop.
package Arrays.Sorting;
public class BubbleSort {
/*
* This method takes a int array as input
* Then sorts the array using BUBBLE SORT algorithm
* Then returns the sorted array
*/
public static int[] sort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
}
}
@AnAverageBeing
Copy link
Author

AnAverageBeing commented Oct 14, 2022

Bubble Sort

it is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high.

Input: arr[] = {5, 1, 4, 2, 8}

First Pass:

Bubble sort starts with very first two elements, comparing them to check which one is greater.
    ( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1. 
    ( 1 5 4 2 8 ) –>  ( 1 4 5 2 8 ), Swap since 5 > 4 
    ( 1 4 5 2 8 ) –>  ( 1 4 2 5 8 ), Swap since 5 > 2 
    ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.

Second Pass:

Now, during second iteration it should look like this:
    ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ) 
    ( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2 
    ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) 
    ( 1 2 4 5 8 ) –>  ( 1 2 4 5 8 ) 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment