-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSortSelection.cpp
55 lines (42 loc) · 1.43 KB
/
SortSelection.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
48
49
50
51
52
53
54
55
// Selection Sort Function
// Takes in an array and sorts it using the selection sort algorithm
#pragma once
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <fstream>
#include <numeric>
#include <vector>
#include "VECTOR.h"
#include "SortSelection.h"
using namespace std;
void selectionSort(NamedVectorObj& vect, ofstream& logfile) {
int i, j, minIndex;
int n = vect.getSize();
// 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);
// For each element in the array except the last one
for (i = 0; i < n - 1; i++) {
// Set minIndex to the current index
minIndex = i;
// Find the index of the minimum element in the remaining unsorted part
for (j = i + 1; j < n; j++) {
if (vect.getIndex(j) < vect.getIndex(minIndex)) {
minIndex = j;
}
}
// Swap the found minimum element with the first element of the unsorted part
if (i != minIndex) { // Only swap if
vect.swapIndex(i, minIndex);
}
// Log the state of the vector after each swap
cout << "After swap " << (i + 1) << ": ";
vect.printData(vect);
}
// Restore the original cout buffer so it points to the console again
cout.rdbuf(coutBuf);
}