Exercise 7.3.3 C++ without Fear 3rd edition

Revise the example so it implements the bubble-sort algorithm,
which is potentially faster than the selection-sort algorithm.
I just need to know what to change or how change the void sort portion of my code to make it a bubble sort algorithm

Thank you in advance

#include "stdafx.h"
#include <iostream>
using namespace std;

void sort(int n);
void swap(int *p1, int *p2);

int a[10];



int main()
{
for (int i = 0; i < 10; ++i) {
cout << "Enter array element #" << i << ": ";
cin >> a[i];
}
sort(10);

cout << "Here is the array, sorted:" << endl;
for (int i = 0; i < 10; ++i) {
cout << a[i] << " ";
}
return 0;
}

void sort(int n) {
int lowest = 0;

for (int i = 0; i < n - 1; ++i) {
lowest = i;
for (int j = i + 1; j < n; ++j) {
if (a[j] < a[lowest]) {
lowest = j;
}
}

if (i != lowest) {
swap(&a[i], &a[lowest]);
}
}
}

void swap(int *p1, int *p2) {
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}
Last edited on
Topic archived. No new replies allowed.