TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
|
This is an implementation of a recursive version of the Bubble sort algorithm More...
#include <algorithm>
#include <array>
#include <cassert>
#include <cstdint>
#include <iostream>
#include <vector>
Go to the source code of this file.
Namespaces | |
namespace | sorting |
for working with vectors | |
Functions | |
template<typename T > | |
void | sorting::recursive_bubble_sort (std::vector< T > *nums, uint64_t n) |
This is an implementation of the recursive_bubble_sort. A vector is passed to the function which is then dereferenced, so that the changes are reflected in the original vector. It also accepts a second parameter of type int and name n , which is the size of the array. | |
static void | test () |
Self-test implementations. | |
int | main () |
Main function. | |
This is an implementation of a recursive version of the Bubble sort algorithm
The working principle of the Bubble sort algorithm.
Bubble sort is a simple sorting algorithm used to rearrange a set of ascending or descending order elements. Bubble sort gets its name from the fact that data "bubbles" to the top of the dataset.
What is Swap?
Swapping two numbers means that we interchange their values. Often, an additional variable is required for this operation. This is further illustrated in the following:
void swap(int x, int y){ int z = x; x = y; y = z; }
The above process is a typical displacement process. When we assign a value to x, the old value of x is lost. That's why we create a temporary variable z to store the initial value of x. z is further used to assign the initial value of x to y, to complete swapping.
Recursion
While the recursive method does not necessarily have advantages over iterative versions, but it is useful to enhance the understanding of the algorithm and recursion itself. In Recursive Bubble sort algorithm, we firstly call the function on the entire array, and for every subsequent function call, we exclude the last element. This fixes the last element for that sub-array.Formally, for ith
iteration, we consider elements up to n-i, where n is the number of elements in the array. Exit condition: n==1; i.e. the sub-array contains only one element.
Complexity Time complexity: O(n) best case; O(n²) average case; O(n²) worst case Space complexity: O(n)
We need to traverse the array n * (n-1)
times. However, if the entire array is already sorted, then we need to traverse it only once. Hence, O(n) is the best case complexity
Definition in file recursive_bubble_sort.cpp.
int main | ( | void | ) |
Main function.
Definition at line 155 of file recursive_bubble_sort.cpp.
|
static |
Self-test implementations.
Definition at line 105 of file recursive_bubble_sort.cpp.