15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

406<br />

Comparing Sorting Algorithms<br />

The quick sort algorithm works nearly identically to merge sort, but quick sort<br />

uses a pivot value to pre-sort values into two different lists. Sorting values by<br />

this pivot value alone makes quick sort generally faster than merge sort.<br />

Basically, the quick sort algorithm works likes this:<br />

1. Pick a pivot value from the list.<br />

2. Divide the list in two, placing values less than the pivot value in the<br />

first list and values greater than the pivot value in the second list.<br />

3. Repeat Steps 1 and 2 until the lists contain only one item.<br />

4. Combine these smaller lists into a larger, sorted list.<br />

The key to speeding up the quick sort algorithm is to choose the proper<br />

pivot <strong>for</strong> dividing each list. The pivot value must be a middle value in a list.<br />

Notice that the merge sort algorithm (see Figure 1-10) still sorts values<br />

through every step whereas pivot values make the quick sort algorithm<br />

(see Figure 1-11) sort the entire list in far fewer steps.<br />

Comparing Sorting Algorithms<br />

To compare the speed of sorting algorithms, computer scientists consider<br />

the following scenarios:<br />

✦ Best-case<br />

✦ Worst-case<br />

✦ Average-case<br />

A best-case scenario measures the speed of different algorithms sorting a<br />

list of values that are already completely sorted. The worst-case scenario<br />

measures the speed of different algorithms sorting a list that’s completely<br />

unsorted. The average-case scenario measures the speed of different algorithms<br />

sorting random values in a list.<br />

To measure the speed and efficiency of an algorithm, computer scientists<br />

measure how much time an algorithm needs to run based on different sizes<br />

of input, which is designated by the letter (n). A small value of (n) means the<br />

input is short whereas a large value of (n) means the input is large.<br />

An algorithm’s efficiency (how fast it runs) is thus based on its input size (n).<br />

In mathematical terms, this is referred to as an order of (n). If an algorithm<br />

runs at the same speed no matter how much data it receives, it’s said to run<br />

at constant time, which can be written in Big-O notation as O(1).

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

Saved successfully!

Ooh no, something went wrong!