Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 13

BUBBLE SORT

MO3AZ
Bubble Sort

The simplest sorting algorithm that works by repeatedly swapping the


adjacent elements if they are in the wrong order.

3 4
1 2

MO3AZ
SAIF
Bubble Sort
Pass #1 :

3 4
1 2

3>1?
Swap
MO3AZ
SAIF
Bubble Sort
Pass #1 :

3 4
1 2

3>4?
No Swap
MO3AZ
SAIF
Bubble Sort
Pass #1 :

3 4
1 2

4>2?
Swap
MO3AZ
SAIF
Bubble Sort
Pass #1 :

3 4
1 2

MO3AZ
SAIF
Bubble Sort
Pass #2 :

3 4
1 2

1>3?
No Swap
MO3AZ
SAIF
Bubble Sort
Pass #2 :

3 4
1 2

3>2?
Swap
MO3AZ
SAIF
Bubble Sort
Pass #2 :

3 4
1 2

MO3AZ
SAIF
Bubble Sort
Pass #3 :

3 4
1 2

1>2?
No Swap
MO3AZ
SAIF
Bubble Sort

3 4
1 2

Sorted !

MO3AZ
SAIF
Bubble Sort
Pseudocode : Example :

function bubbleSort(arr , n ): 3 1 4 2

for i from 0 to n-1: 3 1 4 2 3 > 1 - Swap

for j from 0 to n-i-1: 1 3 4 2 3 > 4 - No Swap


if arr[j] > arr[j+1]:
1 3 4 2 4 > 2 - Swap
swap(arr[j], arr[j+1])
1 3 2 4 1 > 3 - No Swap

Time Complexity in any case : O( ) 1 3 2 4 3 > 2 - Swap

1 2 3 4 1 > 2 - No Swap

1 2 3 4

MO3AZ
SAIF
QUESTIONS TIME !

MO3AZ

You might also like