-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSortBubble.cpp
47 lines (35 loc) · 1.2 KB
/
SortBubble.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Bubble Sort Function
// Takes in an array and sorts it using a bubble sort algorithm
#pragma once
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <numeric>
#include <vector>
#include "VECTOR.h"
#include "SortBubble.h"
using namespace std;
void bubbleSort(NamedVectorObj& vect, ofstream& logfile) {
int n = vect.getSize();
bool swapped = false;
// Save the original buffer of cout
auto coutBuf = cout.rdbuf();
// Redirect cout to logfile
cout.rdbuf(logfile.rdbuf());
// Log initial array state
cout << "Initial array: ";
vect.printData(vect);
do {
swapped = false; // Reset flag to false on each new pass
for (int i = 0; i < n - 1; i++) {
if (vect.getIndex(i) > vect.getIndex(i + 1)) {
vect.swapIndex(i, i + 1);
swapped = true; // Set flag to true if a swap is made
}
// Log the state of the vector after each swap
cout << "After swap " << (i + 1) << ": ";
vect.printData(vect);
}
} while (swapped); // Continue until no more swaps are needed
// Restore the original cout buffer so it points to the console again
cout.rdbuf(coutBuf);
}