Question 2 - Bubble Sort

 avatar
itsLu
c_cpp
2 months ago
808 B
3
Indexable
Never
/* 2- {5, 3, 8, 6, 2, 9, 7, 1}
Show the steps to sort these numbers using bubble sort
algorithm and write the code. */
#include <iostream>
using namespace std;

void Bubble_Sort(int arr[], int n)
{
    int p, c, temp;
    bool isSwapped;
    for (p = 0 ; p < n - 1 ; p++)
    {
        isSwapped = false;
        for (c = 0 ; c < n - p - 1 ; c++)
        {
            if (arr[c] > arr[c+1])
            {
                temp = arr[c];
                arr[c] = arr[c+1];
                arr[c+1] = temp;
                isSwapped = true;
            }
        }
        if (isSwapped == false)
            break;
    }
}

int main ()
{
    int arr[8] = {5, 3, 8, 6, 2, 9, 7, 1};
    Bubble_Sort(arr, 8);
    for (int k = 0 ; k < 8 ; k++)
        cout << arr[k] << "\t";
}
Leave a Comment