> [!NOTE] Definition (Bubble-sort Pseudocode) > ```pseudo \begin{algorithm} \caption{Bubble-sort} \begin{algorithmic} \Input{An array $A[1,2...,n]$} \For{$i=1,...,n-1$} \For{$j=1,...,n-1$} \If{$A[j]>A[j+1]$} \State $X \gets A[j];$ \\ $A[j] \gets A[j+1];$ \\ $A[j+1] \gets X;$ \EndIf \EndFor \EndFor \end{algorithmic} \end{algorithm} ``` # Properties By [[Correctness of Bubble Sort]], bubble sort is finite and correctly sorts the array. By [[Bubble Sort has Quadratic Worst-case Asymptotic Running Time]], ... # Implementation ### Python ```run-python def bubbleSort(A): for i in range(0,len(A)-1): for j in range(0,len(A)-1): if A[j] > A[j+1]: X = A[j] A[j] = A[j+1] A[j+1] = X A = [3,2,1] bubbleSort(A) print(A) ``` ### CPP ```run-cpp # include <iostream> void bubbleSort(int A[], int n) { for (int i = 0; i<n-1; i++) { for (int j=0; j<n-1; j++) { if (A[j]>A[j+1]) { int X = A[j]; A[j] = A[j+1]; A[j+1] = X; } } } } void main() { int A[3] = {1,2,3}; bubbleSort(A,3); for (int i: A) { std::cout << i << "\n"; } } ```