Answer to Question #287275 in C++ for mobi

Question #287275

Use bubble sort to sort following elements: 42, 78, 12, 32, 7, 54, 22, 3


1
Expert's answer
2022-01-13T07:47:08-0500
#include <iostream>
#include <iomanip>
using namespace std;

void Swap(int& a, int& b) {
    int tmp = a;
    a = b;
    b = tmp;
}

void PrintArray(int A[], int n) {
    for (int i=0; i<n; i++) {
        cout << setw(2) << A[i] << (i == n-1 ? "\n" : ", ");
    }
}


void BubbleSort(int A[], int n) {
    bool swapped = true;
    int pass=0;

    cout << "Inital array:   ";
    PrintArray(A, n);
    while (swapped) {
        pass++;
        swapped = false;
        for (int i=1; i<n; i++) {
            if (A[i-1] > A[i]) {
                Swap(A[i-1], A[i]);
                swapped = true;
            }
        }
        cout << "After " << pass << " passes: ";
        PrintArray(A, n);
    }
}

int main() {
    int A[] = {42, 78, 12, 32, 7, 54, 22, 3};
    int n = sizeof(A)/sizeof(A[0]);
    BubbleSort(A, n);

    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment