# Bubble Sort in Data Structures

## Bubble Sort in C++

The bubble sort algorithm analyses two adjacent elements and swaps them until they are no longer in the desired order.

Each iteration moves each member of the array closer to the end, similar to how air bubbles rise to the surface of water. As a result, it's known as a bubble sort.

## Algorithm of Bubble Sorting

In order to sort an array of n elements in increasing order, use the following commands:

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

## How Bubble Sort Works?

Assume we're attempting to organise the components ascending.

- The Initial Iteration (Compare and Swap)

- Compare the first and second items starting with the first index.
- The first and second elements are switched if the first is bigger than the second.

- Compare and contrast the second and third items. If they're not in the right sequence, swap them.

- The procedure continues until the last piece is compared.

The Latter Iteration

- The remaining iterations follow the same pattern.
- The biggest element among the unsorted items is placed at the conclusion of each iteration.

- The comparison takes place up to the final unsorted element in each iteration.

- When all of the unsorted items are placed in their right placements, the array is sorted.

## Code for Bubble Sort in C

```
// Bubble sorting in C
#include <stdio.h>
// carry out the bubble sort
void bubbleSort(int str[], int size) {
// loop over each str element
for (int step = 0; step < size - 1; ++step) {
// str element comparison loop
for (int i = 0; i < size - step - 1; ++i) {
// compare two components that are adjacent
// To sort in descending order, replace > to <.
if (str[i] > str[i + 1]) {
// Swapping happens when items are not in the correct sequence.
int temp = str[i];
str[i] = str[i + 1];
str[i + 1] = temp;
}
}
}
}
// str printing
void printStr(int str[], int size) {
for (int i = 0; i < size; ++i) {
printf("%d ", str[i]);
}
printf("\n");
}
int main() {
int str[] = {-9, 46, 0, 17, -12};
// determine the length of the array
int size = sizeof(str) / sizeof(str[0]);
bubbleSort(str, size);
printf("Array Sorted in Ascending Order:\n");
printArray(str, size);
}
```

The following output should be generated by this programme:

**Output**

```
Array Sorted in Ascending Order:
-12 -9 0 17 46
```

## Bubble Sort Algorithm with Improvements

- Even if the array is already sorted, the above technique does all comparisons.
- This lengthens the execution process.
- We can remedy this by swapping in an additional variable. If elements are swapped, the value of swapped is set to true. If not, it is set to false.
- If no swapping occurs after an iteration, the value of swapped will be false. This indicates that the items have already been sorted and that no additional iterations are required.
- This shortens the execution time and aids in the optimization of the bubble sort.

## The optimised bubble sort algorithm is

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

## Bubble Sort in C code that is optimised

```
// Bubble sort in C that is optimised
#include <stdio.h>
// carry out the bubble sort
void bubbleSort(int str[], int size) {
// loop over the str elements
for (int step = 0; step < size - 1; ++step) {
// determine whether or not swapping happens
int swapped = 0;
// to compare str members in a loop
for (int i = 0; i < size - step - 1; ++i) {
// two str items are compared
// To sort in descending order, replace > to <.
if (str[i] > str[i + 1]) {
// Swapping happens when items are not in the correct sequence.
int temp = str[i];
str[i] = str[i + 1];
str[i + 1] = temp;
swapped = 1;
}
}
// The absence of swapping indicates that the str is already sorted.
// hence there is no need for further comparison
if (swapped == 0) {
break;
}
}
}
// str printing
void printStr(int str[], int size) {
for (int i = 0; i < size; ++i) {
printf("%d ", str[i]);
}
printf("\n");
}
// primary method
int main() {
int str[] = {-9, 46, 0, 17, -12};
// determine the length of the array
int size = sizeof(str) / sizeof(str[0]);
bubbleSort(str, size);
printf("Array Sorted in Ascending Order:n");
printArray(str, size);
}
```

The following output should be generated by this programme:

**Output**

```
Array Sorted in Ascending Order:
-12 -9 0 17 46
```

## Complexity for Bubble Sort

Time Complexity | |

Best Case | O(n) |

Worst Case | O(n^{2}) |

Average | O(n^{2}) |

Space Complexity | O(1) |

Stability | Yes |

## Detail-oriented complexity

The nearby components are compared in Bubble Sort.

Cycle | Number of comparisons |

1^{st} | ( n-1 ) |

2^{nd} | ( n-2 ) |

3^{rd} | ( n-3 ) |

Last | 1 |

As a result, the number of iterations is:

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

That almost equals n^{2}

As a result, Complexity: O (n^{2})

Also, as we can see from the code, bubble sort necessitates two loops. As a result, the complexity is n*n = n^{2}.

## Complexities of Time

**Complexity in the worst-case scenario: O (n**^{2})- The worst case scenario happens if we wish to sort in ascending order but the array is in descending order.

**Complexity in the Best-Case Scenario: O (n)**- When the array has already been sorted, the outer loop repeats n times, but the inner loop does not. As a result, there are only n possible comparisons. As a result, complexity follows a linear pattern.

**Case Complexity on the Average: O (n**^{2})- When the items of an array are jumbled together, this happens (neither ascending nor descending).

## Complexity of Space

- Because an additional variable is utilised for swapping, the space complexity is O(1).
- Two more variables are utilised in the improved bubble sort method. As a result, the spatial complexity will be O(2).

## Applications for Bubble Sorting

If you're using bubble sort,

- Complexity is irrelevant.
- Code that is short and basic is desirable.