snippetcppMinor
C++ Interrupted Bubble Sort
Viewed 0 times
sortbubbleinterrupted
Problem
I've written an interrupted bubble sort, which prints the intermediate result after some specified number of iterations of bubble sort. But I seem to have an speed issue. Could anyone help me spot some places that need to be optimized or are just plain wrong?
#include
#include
#include
#include
#include
using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::ifstream;
using std::stoi;
using std::stringstream;
template
void printVector(vector vect) {
for(int i = 0; i
void swap(T &elementOne, T &elementTwo) {
T temp = elementOne;
elementOne = elementTwo;
elementTwo = temp;
}
void bubbleSort(vector numbers, long int iterations) {
for(int i = 0; i numbers[j + 1]) {
swap(numbers[j], numbers[j + 1]);
}
}
}
printVector(numbers);
}
void parse(string line) {
size_t delimiterPos = line.find("|");
long int iterations = stol(line.substr(delimiterPos + 1));
string numbersString = line.substr(0, delimiterPos - 1);
stringstream numbersSS(numbersString);
vector numbers;
int tempNum;
while(numbersSS >> tempNum) {
numbers.push_back(tempNum);
}
bubbleSort(numbers, iterations);
}
int main(int argc, const char * argv[]) {
ifstream file(argv[1]);
string line;
while(getline(file, line)) {
parse(line);
}
return 0;
}Solution
-
Single Responsibility
As written,
and use it as in
-
Kudos for not
-
The code seems to implement interrupted bubble sort correctly. I don't really understand the expected outcome of the assignment so no comments on the speed.
Single Responsibility
As written,
parse parses data and sorts them. This is plain wrong. Same goes for bubbleSort which sorts and prints. I recommend to change parse tolong int parse(string line, vector& numbers);and use it as in
vector data;
while (getline(file, line)) {
long int iterations = parse(line, data);
bubbleSort(data, iterations);
printVector(data);
}-
Kudos for not
using namespace std!-
The code seems to implement interrupted bubble sort correctly. I don't really understand the expected outcome of the assignment so no comments on the speed.
Code Snippets
long int parse(string line, vector<int>& numbers);vector<int> data;
while (getline(file, line)) {
long int iterations = parse(line, data);
bubbleSort(data, iterations);
printVector(data);
}Context
StackExchange Code Review Q#118190, answer score: 2
Revisions (0)
No revisions yet.