You are on page 1of 11

utm_source programiz top

PRO Preparation with


Thank you for printing our content at www.domain-name.com.
bar&utm_campaign=programiz&utm_medium=referral)
Please check back soon for new
contents.
36% OFF Programiz PRO
Claim Your Discount

Search tutorials & examples


(/)
www.domain-name.com

(https://srv.carbonads.net/ads/click/x/GTND42JUCA
segment=placement:wwwprogramizcom;)
ADS VIA CARBON
(HTTP://CARBONADS.NET/?
M_SOURCE=WWWPROGRAMIZCOM&UTM_MEDIUM=AD_VIA_LINK&UTM_CAMPAIGN=IN_UNIT&UTM_TERM=CARBON)

Bubble Sort
In this tutorial, you will learn about the bubble sort
algorithm and its implementation in Python, Java, C, and
C++.

Bubble sort is a sorting algorithm


(https://www.programiz.com/dsa/sorting-algorithm) that
compares two adjacent elements and swaps them until
they are in the intended order.

Just like the movement of air bubbles in the water that rise
up to the surface, each element of the array move to the
end in each iteration. Therefore, it is called a bubble sort.

Working of Bubble Sort


Suppose we are trying to sort the elements in ascending
order.
Try hands-on
(https://programiz.pro/course/python-interview-questions?
CODING Interview utm source=programiz-top-
utm_source programiz top
PRO 1. First
ourIteration
Preparation
Thank you for printing content at(Compare
with and Swap) Please check back soon for new
www.domain-name.com.
bar&utm_campaign=programiz&utm_medium=referral)
contents.
36% OFF Programiz PRO
1. Starting
Claim from the first index, compare the first and the
Your Discount
second Search
elements.
tutorials & examples
(/)
2. If the first element is greater than the second element,
www.domain-name.com
they are swapped.

3. Now, compare the second and the third elements.


Swap them if they are not in order.

4. The above process goes on until the last element.

Compare the Adjacent Elements

2. Remaining Iteration

The same process goes on for the remaining iterations.

After each iteration, the largest element among the


unsorted elements is placed at the end.
Try hands-on
(https://programiz.pro/course/python-interview-questions?
CODING Interview utm source=programiz-top-
utm_source programiz top
PRO Preparation with
Thank you for printing our content at www.domain-name.com.
bar&utm_campaign=programiz&utm_medium=referral)
Please check back soon for new
contents.
36% OFF Programiz PRO
Claim Your Discount

Search tutorials & examples


(/)
www.domain-name.com

Put the largest element at the end

In each iteration, the comparison takes place up to the


last unsorted element.

Compare the adjacent elements

The array is sorted when all the unsorted elements are


placed at their correct positions.

Try hands-on
(https://programiz.pro/course/python-interview-questions?
CODING Interview utm source=programiz-top-
utm_source programiz top
PRO Preparation with
Thank you for printing our content at www.domain-name.com.
bar&utm_campaign=programiz&utm_medium=referral)
Please check back soon for new
contents.
36% OFF Programiz PRO
Claim Your Discount

Search tutorials & examples


(/)
www.domain-name.com

The array is sorted if all elements are kept in the right order

Bubble Sort Algorithm

bubbleSort(array)
for i <- 1 to indexOfLastUnsortedElement-1
if leftElement > rightElement
swap leftElement and rightElement
end bubbleSort

Bubble Sort Code in Python, Java and


C/C++

Python Java C C++

Try hands-on
(https://programiz.pro/course/python-interview-questions?
CODING Interview utm source=programiz-top-
utm_source programiz top
PRO Preparation with
Thank you for printing our content at www.domain-name.com.
bar&utm_campaign=programiz&utm_medium=referral)
Please check back soon for new
contents.
36% OFF Programiz PRO
# Bubble sort in Python
Claim Your Discount
def bubbleSort(array):
Search tutorials & examples
(/)
# loop to access each array element
www.domain-name.com
for i in range(len(array)):

# loop to compare array elements


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

# compare two adjacent elements


# change > to < to sort in descending order
if array[j] > array[j + 1]:

# swapping elements if elements


# are not in the intended order
temp = array[j]
array[j] = array[j+1]
array[j+1] = temp

data = [-2, 45, 0, 11, -9]

bubbleSort(data)

print('Sorted Array in Ascending Order:')


print(data)

Optimized Bubble Sort Algorithm


In the above algorithm, all the comparisons are made
even if the array is already sorted.

This increases the execution time.

Try hands-on
(https://programiz.pro/course/python-interview-questions?
CODING Interview utm source=programiz-top-
utm_source programiz top
PRO Preparation with
Thank you for printing our content at www.domain-name.com.
bar&utm_campaign=programiz&utm_medium=referral)
Please check back soon for new
contents.
36% OFF Programiz PRO
Claim Your Discount

Search tutorials & examples


(/)
To solve this, we can introduce an extra variable
www.domain-name.com swapped .
The value of swapped is set true if there occurs swapping
of elements. Otherwise, it is set false.

After an iteration, if there is no swapping, the value of


swapped will be false. This means elements are already
sorted and there is no need to perform further iterations.

This will reduce the execution time and helps to optimize


the bubble sort.

Algorithm for optimized bubble sort is

bubbleSort(array)
swapped <- false
for i <- 1 to indexOfLastUnsortedElement-1
if leftElement > rightElement
swap leftElement and rightElement
swapped <- true
end bubbleSort

Optimized Bubble Sort in Python, Java,


and C/C++

Python Java C C++

Try hands-on
(https://programiz.pro/course/python-interview-questions?
CODING Interview utm source=programiz-top-
utm_source programiz top
PRO Preparation with
Thank you for printing our content at www.domain-name.com.
bar&utm_campaign=programiz&utm_medium=referral)
Please check back soon for new
contents.
36% OFF Programiz PRO Bubble sort in Python
# Optimized
Claim Your Discount
def bubbleSort(array):
Search tutorials & examples
(/)
# loop through each element of array
www.domain-name.com
for i in range(len(array)):

# keep track of swapping


swapped = False

# loop to compare array elements


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

# compare two adjacent elements


# change > to < to sort in descending order
if array[j] > array[j + 1]:

# swapping occurs if elements


# are not in the intended order
temp = array[j]
array[j] = array[j+1]
array[j+1] = temp

swapped = True

# no swapping means the array is already sorted


# so no need for further comparison
if not swapped:

Bubble Sort Complexity

Time Complexity  

Best O(n)

Worst O(n2)

Average O(n2)

Space Complexity O(1)

Stability Yes

Try hands-on
(https://programiz.pro/course/python-interview-questions?
CODING Interview utm source=programiz-top-
utm_source programiz top
PRO Complexity
Preparation
Thank you for printing with
our contentinatDetail
www.domain-name.com.
bar&utm_campaign=programiz&utm_medium=referral)
Please check back soon for new
contents.
36% OFF Programiz PRO
Bubble
Claim YourSort compares the adjacent elements.
Discount

Search tutorials & examples


(/)
Cycle Number of Comparisons
www.domain-name.com
1st (n-1)

2nd (n-2)

3rd (n-3)

....... ......

last 1

Hence, the number of comparisons is

(n-1) + (n-2) + (n-3) +.....+ 1 = n(n-1)/2

nearly equals to n2

Hence, Complexity: O(n2)

Also, if we observe the code, bubble sort requires two


loops. Hence, the complexity is n*n = n2

1. Time Complexities

Worst Case Complexity: O(n2)

If we want to sort in ascending order and the array is in


descending order then the worst case occurs.

Best Case Complexity: O(n)

If the array is already sorted, then there is no need for


sorting.

Average Case Complexity: O(n2)

It occurs when the elements of the array are in jumbled


order (neither ascending nor descending).

Try hands-on
(https://programiz.pro/course/python-interview-questions?
CODING Interview utm source=programiz-top-
utm_source programiz top
PRO 2. Space
Preparation
Thank you for printing Complexity
with
our content at www.domain-name.com.
bar&utm_campaign=programiz&utm_medium=referral)
Please check back soon for new
contents.
36% OFF Programiz PRO
ClaimSpace complexity is O(1) because an extra variable is
Your Discount
used forSearch
swapping.
tutorials & examples
(/)
In the optimizedwww.domain-name.com
bubble sort algorithm, two extra
variables are used. Hence, the space complexity will
be O(2) .

Bubble Sort Applications


Bubble sort is used if

complexity does not matter

short and simple code is preferred

Similar Sorting Algorithms


Quicksort (/dsa/quick-sort)

Insertion Sort (/dsa/insertion-sort)

Merge Sort (/dsa/merge-sort)

Selection Sort (/dsa/selection-sort)

Next Tutorial:
(/dsa/selection-sort)
Selection Sort

Previous Tutorial:
Bellman Ford's (/dsa/bellman-ford-
algorithm)
Algorithm

Share on:
Try hands-on
(https://programiz.pro/course/python-interview-questions?
CODING Interview utm source=programiz-top-
utm_source programiz top
PRO (https://www.facebook.com/sharer/sharer.php?
Preparation with
Thank you for printing our content at www.domain-name.com. (https://twitter.com/inte
bar&utm_campaign=programiz&utm_medium=referral)
Please check back soon for new
contents.
36% OFF u=https://www.programiz.com/dsa/bubble-sort)
Programiz PRO text=Check%20this%20
sort)
Claim Your Discount

Search tutorials & examples


(/)
Did you find this article helpful?
www.domain-name.com

Related Tutorials

DS & Algorithms

Selection Sort Algorithm

(/dsa/selection-sort)

DS & Algorithms

Insertion Sort Algorithm

(/dsa/insertion-sort)
Try hands-on
DS & Algorithms (https://programiz.pro/course/python-interview-questions?
CODING Interview utm source=programiz-top-
utm_source programiz top
PRO Shell Sort
Preparation Algorithm
with
Thank you for printing our content at www.domain-name.com.
bar&utm_campaign=programiz&utm_medium=referral)
Please check back soon for new
contents.
36% OFF Programiz PRO
Claim Your Discount

Search tutorials & examples


(/dsa/shell-sort)
(/)
www.domain-name.com
DS & Algorithms

Counting Sort Algorithm

(/dsa/counting-sort)

You might also like