12.07.2015 Views

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

242 Chap. 7 Internal Sorting4220171328142315i=0 1 2 3 4 5 61320174228142315131417422820231513141542282023171314151728202342131415172028234213141517202328421314151720232842Figure 7.3 An example of Selection Sort. Each column shows the array after theiteration with the indicated value of i in the outer for loop. Numbers above theline in each column have been sorted <strong>and</strong> are in their final positions.Key = 42Key = 5Key = 23Key = 10(a)Key = 42Key = 5Key = 23Key = 10(b)Figure 7.4 An example of swapping pointers <strong>to</strong> records. (a) A series of fourrecords. The record with key value 42 comes before the record with key value 5.(b) The four records after the <strong>to</strong>p two pointers have been swapped. Now the recordwith key value 5 comes before the record with key value 42.remember the position of the element <strong>to</strong> be selected <strong>and</strong> do one swap at the end.Thus, the number of comparisons is still Θ(n 2 ), but the number of swaps is muchless than that required by bubble sort. Selection Sort is particularly advantageouswhen the cost <strong>to</strong> do a swap is high, for example, when the elements are long stringsor other large records. Selection Sort is more efficient than Bubble Sort (by aconstant fac<strong>to</strong>r) in most other situations as well.There is another approach <strong>to</strong> keeping the cost of swapping records low thatcan be used by any sorting algorithm even when the records are large. This is<strong>to</strong> have each element of the array s<strong>to</strong>re a pointer <strong>to</strong> a record rather than s<strong>to</strong>re therecord itself. In this implementation, a swap operation need only exchange thepointer values; the records themselves do not move. This technique is illustratedby Figure 7.4. Additional space is needed <strong>to</strong> s<strong>to</strong>re the pointers, but the return is afaster swap operation.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!