Department of Computer Science | Institute of Theoretical Computer Science | CADMO

Theory of Combinatorial Algorithms

Prof. Emo Welzl and Prof. Bernd Gärtner

// Prog: merge_sort.cpp // implements and tests merge-sort on random input #include #include #include typedef std::vector::iterator Vit; // PRE: [begin, middle), [middle, end) are valid ranges; in // both of them, the elements are in ascending order void merge (Vit begin, Vit middle, Vit end) { const int n = end - begin; // total number of cards std::vector deck(n); // new deck to be built Vit left = begin; // top card of left deck Vit right = middle; // top card of right deck for (Vit d = deck.begin(); d != deck.end(); ++d) // put next card onto new deck if (left == middle) *d = *right++; // left deck is empty else if (right == end) *d = *left++; // right deck is empty else if (*left < *right) *d = *left++; // smaller top card left else *d = *right++; // smaller top card right // copy new deck back into [begin, end) Vit d = deck.begin(); while (begin != middle) *begin++ = *d++; while (middle != end) *middle++ = *d++; } // PRE: [begin, end) is a valid range // POST: the elements *p, p in [begin, end) are in ascending order void merge_sort (Vit begin, Vit end) { const int n = end - begin; if (n <= 1) return; // nothing to do const Vit middle = begin + n/2; merge_sort (begin, middle); // sort first half merge_sort (middle, end); // sort second half merge (begin, middle, end); // merge both halfs } int main() { // input of number of values to be sorted int n; std::cin >> n; std::vector v(n); std::cout << "Sorting " << n << " integers...\n"; // create sequence: for (int i=0; i