To address the problem, follow the instructions below:

  1. Use a nested for loop to traverse the input array, using two variables I and j, so that 0 I n-1 and 0 j n-i-1 are returned.
  2. If arr[j] is bigger than arr[j+1], swap these neighboring items; else, continue.
  3. Print the array that has been sorted.

Time Complexity: O(N2)


#include <bits/stdc++.h>
using namespace std;

void bubbleSort(int arr[], int n)
{
    int i, j;
    for (i = 0; i < n - 1; i++)

        for (j = 0; j < n - 1; j++)
        {
            if (arr[j] > arr[j + 1])
            {
                swap(arr[j], arr[j + 1]);
            }
        }
}

// Driver code
int main()
{
    int arr[] = {22, 14, 12, 18, 9};
    int N = 5;
    bubbleSort(arr, N);
    cout << "Sorted array: ";
    for (int i = 0; i < N; i++)
        cout << arr[i] << " ";
    cout << endl;
    return 0;
}

Output

Sorted array: 9 12 14 18 22