lecture-9

# Lecture-9

This preview shows page 1. Sign up to view the full content.

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Sorting Exercises CPSC 223  ­ ­ Fall 2010 5 9/28/10 Evaluating Sorting Algorithms Number of comparisons –  How many pairs of items are compared within a pass Number of moves –  How many times do we move list items –  Within a list or to a temporary variable •  We often do “swaps” void swap(int& x, int& y) // here just integers { int tmp = x; How many moves in a swap? x = y; 3 y = tmp; } CPSC 223  ­ ­ Fall 2010 Selection Sort The basic idea –  Select (i.e., “ﬁnd”) the largest item –  Swap it with the last item in the list –  Repeat with items 0 to n – 2 –  Stop when only one item left Pass 1 Ini6al list: 29 10 14 13 (n=4) 13 10 14 29 Pass 2 Pass 3 13 10 14 29 13 10 14 29 13 10 14 29 10 13 14 29 CPSC 223  ­ ­ Fall 2010 6 9/28/10 Selection Sort (based on textbook) void selectionSort(Entry theArray, int n) { for(int i = n - 1; i >= 1; i--) { // passes 1..n-1 int index = 0; for(int j = 1; j < i + 1; j++) { // passes 1..i if(theArray[j] >= theArray[index]) index = j; // not 1 move } // end inner for swap(theArray[index], theArray[i]); // 3 moves } // end outer for } CPSC 223  ­ ­ Fall 2010 Bubble Sort The basic idea:...
View Full Document

## This document was uploaded on 03/18/2014 for the course CPSC 223 at Gonzaga.

Ask a homework question - tutors are online