lecture-9

# Sorted i sorted true forint j 0 j n i j

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: –  Compare adjacent items … –  Exchange items if they are out of order –  Repeat for n – 1 passes –  Each pass p requires n – p comparisons Pass 2 Pass 3 Ini6al list: 29 10 14 13 (n=4) 10 29 14 13 10 14 13 29 10 13 14 29 10 14 13 29 10 13 14 29 10 14 29 13 10 13 14 29 Pass 1 10 14 13 29 CPSC 223  ­ ­ Fall 2010 7 9/28/10 Bubble Sort (based on textbook) void bubbleSort(Entry theArray, int n) { bool sorted = false; for(int i = 1; i < n && !sorted; i++) { sorted = true; for(int j = 0; j < (n – i); j++) { if(theArray[j] > theArray[j+1]) { swap(theArray[j], theArray[j+1]); sorted = false; } } // end inner for } // end outer for } CPSC 223  ­ ­ Fall 2010 Insertion Sort The basic idea: –  Partition list into sorted and unsorted regions –  Select ﬁrst item in unsorted region –  Insert item into the right location of sorted region –  Shift larger items one location forward in the list Pass 2 Pass 3 Ini6al list: 29 10 14 13 (n=4) 29 10 14 13 10 29 14 13 10 14...
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