CS253

CS253: Software Development with C++

Spring 2017

Sort Algorithm

See this page as a slide show

Sort Algorithm

CS253 Sort Algorithm

The sort algorithm

The sort algorithm (from the header file <algorithm>) has two forms:

Containers

Default comparison

string s = "Kokopelli";
sort(s.begin(), s.end());
cout << s << '\n';
Keiklloop

Explicit comparison

string s = "Kokopelli";
sort(s.begin(), s.end(), less<char>);
cout << s << '\n';
c.cc:2: error: expected primary-expression before ')' token

Explicit comparison

string s = "Kokopelli";
sort(s.begin(), s.end(), less<char>());
cout << s << '\n';
Keiklloop

Reverse sort

string s = "Kokopelli";
sort(s.begin(), s.end(), greater<char>());
cout << s << '\n';
poollkieK

Comparison function

bool compare(char a, char b) {
    return a < b;
}

int main() {
    string s = "Kokopelli";
    sort(s.begin(), s.end(), compare);
    cout << s << '\n';
}
Keiklloop

λ-function

string s = "Kokopelli";
sort(s.begin(), s.end(),
     [](char a, char b){return a<b;});
cout << s << '\n';
Keiklloop

Case folding

bool compare(char a, char b) {
    return toupper(a) < toupper(b);
}

int main() {
    string s = "Kokopelli";
    sort(s.begin(), s.end(), compare);
    cout << s << '\n';
}
eiKklloop

Unique

If you want to avoid duplicates, then use unique.

bool compare(char a, char b) {
    return toupper(a) < toupper(b);
}

int main() {
    string s = "Kokopelli";
    sort(s.begin(), s.end(), compare);
    auto it = unique(s.begin(), s.end());
    s.resize(it-s.begin());
    cout << s << '\n';
}
eiKklop

Modified: 2017-04-20T22:16

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building