0% found this document useful (0 votes)
24 views

Sorting ALGO

Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. It has a worst-case time complexity of O(n2) making it slow for large data sets. The algorithm makes multiple passes through the list, moving unordered items to their correct positions each pass. Recursive bubble sort works by recursively calling the function on smaller and smaller portions of the array until the base case of a single element is reached.

Uploaded by

Sanket
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Sorting ALGO

Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. It has a worst-case time complexity of O(n2) making it slow for large data sets. The algorithm makes multiple passes through the list, moving unordered items to their correct positions each pass. Recursive bubble sort works by recursively calling the function on smaller and smaller portions of the array until the base case of a single element is reached.

Uploaded by

Sanket
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Bubble Sort – Data Structure and Algorithm

Tutorials
Bubble Sort is the simplest sorting algorithm that repeatedly swaps the
adjacent elements if they are in the wrong order. This algorithm is unsuitable
for large data sets as its average and worst-case time complexity is quite
high.
Bubble Sort Algorithm
In the Bubble Sort algorithm,
 Traverse from the left and compare adjacent elements and the higher one
is placed at the right side.
 In this way, the largest element is moved to the rightmost end at first.
 This process is then continued to find the second largest and place it and
so on until the data is sorted.

How does Bubble Sort Work?


Let us understand the working of bubble sort with the help of the following
illustration:

 Total no. of passes: n-1


 Total no. of comparisons: n*(n-1)/2

Advantages of Bubble Sort:


 Bubble sort is easy to understand and implement.
 It does not require any additional memory space.
 It is a stable sorting algorithm, meaning that elements with the same key
value maintain their relative order in the sorted output.
Disadvantages of Bubble Sort:
 Bubble sort has a time complexity of O(N2) which makes it very slow for
large data sets.
 Bubble sort is a comparison-based sorting algorithm, which means that it
requires a comparison operator to determine the relative order of
elements in the input data set. It can limit the efficiency of the algorithm in
certain cases.
Some FAQs related to Bubble Sort:
What is the Boundary Case for Bubble sort?
Bubble sort takes minimum time (Order of n) when elements are already
sorted. Hence it is best to check if the array is already sorted or not
beforehand, to avoid O(N2) time complexity.
Does sorting happen in place in Bubble sort?
Yes, Bubble sort performs the swapping of adjacent pairs without the use of
any major data structure. Hence Bubble sort algorithm is an in-place
algorithm.
Is the Bubble sort algorithm stable?
Yes, the bubble sort algorithm is stable.

Where is the Bubble sort algorithm used?


Due to its simplicity, bubble sort is often used to introduce the concept of a
sorting algorithm. In computer graphics, it is popular for its capability to
detect a tiny error (like a swap of just two elements) in almost-sorted arrays
and fix it with just linear complexity (2n).
Example: It is used in a polygon filling algorithm, where bounding lines are
sorted by their x coordinate at a specific scan line (a line parallel to the x-
axis), and with incrementing y their order changes (two elements are
swapped) only at intersections of two lines.

Recursive Bubble Sort


Bubble Sort is the simplest sorting algorithm that works by repeatedly
swapping the adjacent elements if they are in wrong order.
Example:
First Pass:
( 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:
( 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 )
Now, the array is already sorted, but our algorithm does not know if it is
completed. The algorithm needs one whole pass without any swap to know
it is sorted.
Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

How to implement it recursively?


Recursive Bubble Sort has no performance/implementation advantages, but
can be a good question to check one’s understanding of Bubble Sort and
recursion.
If we take a closer look at Bubble Sort algorithm, we can notice that in first
pass, we move largest element to end (Assuming sorting in increasing
order). In second pass, we move second largest element to second last
position and so on.
Recursion Idea.
1. Base Case: If array size is 1, return.
2. Do One Pass of normal Bubble Sort. This pass fixes last element of
current subarray.
3. Recur for all elements except last of current subarray.

// Java program for recursive implementation


// of Bubble sort

import java.util.Arrays;

public class GFG


{
// A function to implement bubble sort
static void bubbleSort(int arr[], int n)
{
// Base case
if (n == 1)
return;

int count = 0;
// One pass of bubble sort. After
// this pass, the largest element
// is moved (or bubbled) to end.
for (int i=0; i<n-1; i++)
if (arr[i] > arr[i+1])
{
// swap arr[i], arr[i+1]
int temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
count = count+1;
}

// Check if any recursion happens or not


// If any recursion is not happen then return
if (count == 0)
return;

// Largest element is fixed,


// recur for remaining array
bubbleSort(arr, n-1);
}

// Driver Method
public static void main(String[] args)
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};

bubbleSort(arr, arr.length);

System.out.println("Sorted array : ");


System.out.println(Arrays.toString(arr));
}
}

 Time Complexity: O(n*n)


 Auxiliary Space: O(n)

1 difference between iterative and recursive bubble sort?


Ans. Recursive bubble sort runs on O(n) auxiliary space complexity whereas
iterative bubble sort runs on O(1) auxiliary space complexity.

2. Which is faster iterative or recursive bubble sort?


Ans. Based on the number of comparisons in each method, the recursive
bubble sort is better than the iterative bubble sort, but the time complexity for
both the methods is same.

Which sorting method we should prefer more iterative or recursive


bubble sort?
Ans. Both the methods complete the computation at the same
time(according to time complexity analysis) but iterative code takes less
memory than recursive one, so we should prefer iterative bubble sort more
than recursive bubble sort.
 Time Complexity Analysis of Bubble Sort:
 Best Case: The best case occurs when the array is already sorted. So
the number of comparisons required is N-1 and the number of swaps
required = 0. Hence the best case complexity is O(N).

 Worst Case: The worst-case condition for bubble sort occurs when
elements of the array are arranged in decreasing order.
In the worst case, the total number of iterations or passes required to sort
a given array is (N-1). where ‘N’ is the number of elements present in the
array.

At pass 1:

Number of comparisons = (N-1)

Number of swaps = (N-1)

At pass 2:

Number of comparisons = (N-2)

Number of swaps = (N-2)

At pass 3:

Number of comparisons = (N-3)

Number of swaps = (N-3)

At pass N-1:

Number of comparisons = 1

Number of swaps = 1

Now, calculating total number of comparison required to sort the array

= (N-1) + (N-2) + (N-3) + . . . 2 + 1

= (N-1)*(N-1+1)/2 { by using sum of N natural Number formula }

= (N * (N-1)) / 2

In worst case, Total number of swaps = Total number of comparison

Total number of comparison (Worst case) = N(N-1)/2

Total number of swaps (Worst case) = N(N-1)/2

So worst case time complexity is O(N2) as N2 is the highest order term.

You might also like