Skip to content

Instantly share code, notes, and snippets.

@fddemora
Last active July 16, 2021 02:52
Show Gist options
  • Save fddemora/d5aa83d11f189af20bd84f56b64ab484 to your computer and use it in GitHub Desktop.
Save fddemora/d5aa83d11f189af20bd84f56b64ab484 to your computer and use it in GitHub Desktop.
cpp selection sort algorithm
/*
Imagine a struct like:
struct Bid {
string title;
string fund;
double amount;
}
Then taking a csv, reading the data into the bid, and then adding it to a vector.
The vector is sent to the function selectionSort(vect) where it is sorted.
*/
void selectionSort(vector<Bid>& bids) { // 14 secs for 18000 records.
// index to the current minimum bid
int min;
int max = bids.size();
// pos is the position within the bids that marks sorted/unsorted
for(unsigned pos = 0; pos < max; pos++){
min = pos;
for (unsigned j = pos+1; j < max; j++) {
if(bids.at(j).title.compare(bids.at(min).title) < 0){ // if arg1 < arg2 -> -1
// set the j value to min if the inner loop value is less than the outer loop pos.
min = j;
}
}
// outer loop after search is done.
if(min != pos) { //
swap(bids.at(pos), bids.at(min)); // std::swap swaps the values of a and b.
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment