Lec18 - Sorting

Lec18 - Sorting - Lecture 18: Introduction to Sorting PIC...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
1 Lecture 18: Introduction to Sorting PIC 10B Todd Wittman Sorting s Sorting a list of items from smallest to largest is a classical and common programming task. s It helps for organizing data, e.g. preparing names for the phonebook. s We’ve seen that sorting can improve searching. s For an unsorted list, linear search is O(N). s For a sorted list, binary search is O(logN). s Today we’re going to look at different methods for sorting a vector of integers. s But the sorting algorithms can be templated to sort any data type for which an ordering is defined (strings, classes with operator<). s Hmm. ... good HW assignment.
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
2 Sorting With a Binary Tree s We’ve already encountered one way to sort a list using a binary tree. s The in-order traversal prints out the values in sorted order. s We could modify the printInOrder function to store the values in a given vector, rather than printing them. template <typename T> if (rootNode != NULL) { sortInOrder (v, rootNode->left); v.push_back (rootNode->data); sortInOrder (v, rootNode->right); } return; } How do we use this function? Sorting With a Binary Tree s To use the function on the last slide, you would have to send it an empty vector and a tree containing your values. sortInOrder (v, myTree); s But wait! We’re usually going to want to sort a vector. s So we would first have to copy our vector v into a tree, clear the vector v, and then put the sorted list back into v. s
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 11/19/2011 for the course PIC 10B taught by Professor Wittman during the Winter '08 term at UCLA.

Page1 / 8

Lec18 - Sorting - Lecture 18: Introduction to Sorting PIC...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online