Skip to main content

Bubble Sort | Java & Python | MyCodingNetwork | Alok Tripathi



Bubble Sort is a simple sorting algorithm that works by repeatedly comparing and swapping adjacent elements in an array until they are in the correct order. It is called bubble sort because the smaller elements "bubble" to the top of the array, while the larger elements sink to the bottom.

Quick Video Explanation:


How Bubble Sort Works

Bubble sort works by iterating through the array from left to right and comparing each pair of adjacent elements. If the element on the left is larger than the element on the right, they are swapped. This way, the largest element in the array moves to the rightmost position in each iteration. This process is repeated until no more swaps are needed, which means the array is sorted.

To illustrate how bubble sort works, let's use the example of sorting the array [30,90,50,10,40] in ascending order.

First Iteration/Pass:

The first step is to compare the first two elements, 30 and 90. Since 30 is smaller than 90, they are already in order and no swap is needed. The array remains [30,90,50,10,40].

The second step is to compare the second and third elements, 90 and 50. Since 90 is larger than 50, they are out of order and need to be swapped. The array becomes [30,50,90,10,40].

The third step is to compare the third and fourth elements, 90 and 10. Since 90 is larger than 10, they are out of order and need to be swapped. The array becomes [30,50,10,90,40].

The fourth step is to compare the fourth and fifth elements, 90 and 40. Since 90 is larger than 40, they are out of order and need to be swapped. The array becomes [30,50,10,40,90].

At this point, we have completed one pass through the array. Notice that the largest element, 90, has moved to the last position. This is a property of bubble sort: after each pass, the largest element in the unsorted part of the array moves to the end.

Second Iteration/Pass:

We repeat the same process for the remaining four elements in the array: [30,50,10,40]. We compare 30 and 50 and find them in order. We compare 50 and 10 and swap them. We compare 50 and 40 and find them in order. The array becomes [30,10,40,50,90].

Third Iteration/Pass:

We repeat the same process for the remaining three elements in the array: [30,10,40]. We compare 30 and 10 and swap them. We compare 30 and 40 and find them in order. The array becomes [10,30,50,40,90].

Fourth Iteration/Pass:

We repeat the same process for the remaining two elements in the array: [10,30]. We compare 10 and 30 and find them in order. The array becomes [10,30,50,40,90].

At this point, we have completed four passes through the array and no more swaps are needed. The array is sorted in ascending order.

Code Snippet:

Java:

int a[]={30,10,40,80,60,20};

int l=a.length;

boolean flag=false;

for(int i=0;i<l-1;i++)

{flag=false;

for(int j=0;j<l-i-1;j++)

{

if(a[j]>a[j+1])

{

//swapping them

int temp=a[j];

a[j]=a[j+1];

a[j+1]=temp;

flag=true;

}

}

if(flag==false)

break;

}

Python:

a=[30,10,40,80,60,20]

l=len(a)

for i in range(0,l-1):

flag=false

    for j in range(0,l-1-i):

        #swapping

        if a[j]>a[j+1]:

            temp=a[j+1]

            a[j+1]=a[j]

            a[j]=temp

flag=true

    if flag==false:

break


print (a)


Conclusion:

Bubble sort has a time complexity of O(n^2), where n is the number of elements in the array. This means that it takes n^2 comparisons to sort an array of n elements. Bubble sort is not very efficient for large arrays because it performs many unnecessary comparisons.

Bubble sort is a stable sorting algorithm, which means that it preserves the relative order of equal elements in the array. For example, if we have an array of names with their ages as [Alice-20, Bob-20, Claire-21, Dave-19], bubble sort will not change the order of Alice and Bob because they have the same age.

Related Video: 

Bubble sort is also an in-place sorting algorithm, which means that it does not use any extra space to sort the array. It only modifies the original array by swapping elements.

More To Explore:

Popular posts from this blog

Pattern 6 | Java | MyCodingNetwork | Alok Tripathi (Code 8)

Problem Statement: Write a program to make a square and mark out its diagonals. Accept the length as input from the user and give output in the following manner: And ( In simple words, we have printed stars (*) on the boundary positions of the matrix and on the centre positions of the matrix we have printed blank space( ) )   THE CODE: Sample Output: In the above program, two int variables r to accept the length of square as input. On line 7, following statement is used to accept the input from the user: int r = sc . nextInt ();   For taking the input Scanner class has been used, more about Scanner class Algorithm: Two for loops are defined: ·         First for loop with counter variable i has initial value 1, conditional statement i less than or equal to r and an updating statement i++ . ·         Inside the first loop there is a second for loop, with counter variable j has ini...

Kadane's Algorithm | The-Algorithm-Drive | MyCodingNetwork

Kadane's Algorithm Kadane’s algorithm is used to find largest contagious subarray sum for a given array. It is one of the most common types of algorithms used to find the subarray with largest sum. The time complexity of this algorithm is O(N) .     Output :            Code Explanation: On line 4, there’s an  int  array variable a[ ], which is the array on which we have to perform our task. We have stored the value of the array, in variable l. cur_max,  is a temporary variable for traversing the array and storing positive sum occurring and update it after each iteration.  global_max , is a variable for storing the highest sum of subarray. ‘ start ’ variable stores the starting index of the desired subarray and ‘ end ’ variable stores the last index of that subarray, that is, contagious subarray with the highest sum. Working: Talking about the working of this algorithm, it uses one for loop and the entire operation can be perfo...

Pattern 4 | Java | MyCodingNetwork | Alok Tripathi (Code 6)

Problem Statement: Write a program to draw the following pattern where number of rows are decided by the user and given to the program as input:         *       * *     * * *   * * * * * * * * * * * * * * * (Take a variable n which takes the number of rows as input from the user, For above example, n=6) OUTPUT: The above program is the extension of the previous program (Pattern #3). This program asks the user to input the number of rows that it wants in the program. For accepting the input, the program has Scanner class which has been extracted from the package java.util . In this program, we will learn how to receive data from the user. If you remember in three previous patterns, the program itself had the input of number of rows where n=8, but now the user will tell the program how many rows are to be added.   Simplification 1.     In Line 1, the java.util  package has been imported, to use the Scanner cl...