CSE 40872 Lecture 010

Topic:Sorting (STL)
Author: Peter Bui <pbui@cse.nd.edu>
Date: September 23, 2009

STL sort

Included in <algorithm> are a variety of sorting functions:

sort(vec.begin(), vec.end());

STL partial_sort

partial_sort(vec.begin(), vec.begin() + 5, vec.end());
partial_sort(vec.begin(), vec.end(), vec.end());

STL stable_sort

stable_sort(lst.begin(), lst.end());

Binary Predicates

Customize sort order with binary predicates:

bool less_length(const string &s1, const string &s2)
{
    return s1.length() < s2.length();
}

bool compare_jobs(const struct job *j1, const struct job *j2)
{
    return j1->priority < j2->priority;
}

sort(vStrings.begin(), vStrings.end(), less_length);
sort(lJobs.begin(), lJobs.end(), compare_jobs);

Builtin Function Objects

Included in <functional> are a variety of function objects:

sort(vInts.begin(), vInts.end(), greater<int>());

Nth element

nth_element(vDists.begin(), vDists.begin() + nth, vDists.end());

Heap Algorithms

// Convert to heap
make_heap(v.begin(), v.end());

// Pop next element out of heap
pop_heap(v.begin(), v.end());
v.pop_back();

// Push new element into heap
v.push_back(7);
push_heap(v.begin(), v.end());

// Convert help to ordered collection
sort_heap(v.begin(), v.end());