Bubble Sort Algorithm
The Bubble Sort Algorithm is a simple and widely-known sorting technique used in computer programming to arrange a list of elements, such as numbers or strings, in a specific order, either ascending or descending. It is named after the process of bubbles rising to the surface in a liquid, as it works by repeatedly stepping through the list and comparing adjacent pairs of elements. If the pair of elements is found to be in the wrong order, they are swapped, effectively "bubbling" the larger element towards the end of the list. This process is repeated until no more swaps are needed, indicating that the list is fully sorted.
Bubble Sort is considered an inefficient algorithm for large datasets due to its high time complexity, which is O(n^2) in the worst and average cases, where n is the number of elements in the list. This means that the algorithm's runtime grows quadratically with the size of the input, making it impractical for extensive lists. However, Bubble Sort has the advantage of being easy to understand and implement, making it suitable for educational purposes or for sorting small datasets where performance is not a critical concern. Furthermore, Bubble Sort is a stable sorting algorithm, meaning that it preserves the relative order of equal elements, which can be a desirable property in certain applications.
/*
Petar 'PetarV' Velickovic
Algorithm: Bubble Sort
*/
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <complex>
#define MAX_N 5001
using namespace std;
typedef long long lld;
int n;
int niz[MAX_N];
//Bubble sort algoritam za sortiranje niza
//Slozenost: O(n^2)
inline void bubbleSort()
{
bool swapped;
int it = 0;
do
{
swapped = false;
for (int i=0;i<n-it-1;i++)
{
if (niz[i] > niz[i+1])
{
swap(niz[i], niz[i+1]);
swapped = true;
}
}
it++;
} while (swapped);
}
int main()
{
n = 5;
niz[0] = 4;
niz[1] = 2;
niz[2] = 5;
niz[3] = 1;
niz[4] = 3;
bubbleSort();
for (int i=0;i<n;i++) printf("%d ",niz[i]);
printf("\n");
return 0;
}