Use bubble sort to sort following elements: 42, 78, 12, 32, 7, 54, 22, 3
#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;
}
Comments
Leave a comment