**Bubble sort in data structure** is used for sorting element in particular order as ascending or descending.

## Bubble sort in data structure

In this technique we compare the first element with preceding element if the number next to that is small then we perform swapping so that the smaller number become a first, Then again go for next preceding number this process will continue till end of iteration and we perform N number of iteration to a sorting element, at last, we will get sorted list.

Using this technique at first iteration we bubble up either the first or last element while arranging in ascending or descending order respectively.

## Bubble sort in c with explanation

**Example:** Consider following a set of numbers and perform bubble sort.

Compare 70 with 50, 50<70 , So perform swapping. Therefore we get.

Compare 70 with 60, 60<70, So perform swapping.

Compare 70 with 20, 20<70 so perform swapping.

Compare 70 with 10, 10<70 so perform swapping.

After iteration 1 we got 70 at its position.

**Iteration 2: **Now start with the first element again.

Compare 50 with 60, 60>50 so don’t change anything move forward.

Compare 60 with 20, 20<60 so swap numbers.

Compare 60 with 10, 10<60 so swap numbers.

After this iteration, we get 60 at its position.

**Iteration 3:**

Compare 50 with 20, 20<50 so swap numbers.

In this iteration, we get 50 at its position.

**Iteration 4:**

Compare 20 with 10, 20>10 so swap numbers.

After this iteration, we got our all element are arranged in ascending order.

**Sorted array – **10 20 50 60 70

**Passes(iteration) required = N-1 = 5-1 =4**

Time complexity for bubble sort worst case **O(n ^{2})**.

## Advantages of bubble sort

- Bubble sort is easy to implement.
- No extra space required while implementation.

## Disadvantages of bubble sort

- It’s not possible to implement bubble sort if we have a large number of the array.
- Not suitable for real-time application.

## Bubble sort algorithm in c

- Start
- Take numbers input from a user
- Traverse the array until the end
- Compare i array index value with i+1 and bubble up large value to end
- print sorted an array
- End

## Bubble sort program in c

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
#include <stdio.h> int main() { int array[100], n, c, d, swap; printf("Enter number of elements\n"); scanf("%d", &n); printf("Enter %d integers\n", n); for (c = 0; c < n; c++) scanf("%d", &array[c]); for (c = 0 ; c < n - 1; c++) { for (d = 0 ; d < n - c - 1; d++) { if (array[d] > array[d+1]) /* For decreasing order use < */ { swap = array[d]; array[d] = array[d+1]; array[d+1] = swap; } } } printf("Sorted list in ascending order:\n"); for (c = 0; c < n; c++) printf("%d\n", array[c]); return 0; } |

**Output of program:**

## Leave a Reply