Basic Sorting Algorithms

# Basic Sorting Algorithms - Lecture 19 Introduction to...

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

1 Lecture 19: 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.

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

View Full Document
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
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 8

Basic Sorting Algorithms - Lecture 19 Introduction to...

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

View Full Document
Ask a homework question - tutors are online