Docsity

3 Algorithms and Data Structures, Exams of Data Structures and Algorithms

Toggle sidebar
bg1
process.snetence
algs
process.word
3 Algorithms and Data Structures
analysis of algorithms. correctness
efficiency
algorithms programs
program verification,
107
to process.sentence :sent
output fput (process.word first :sent) (process.sentence bf :sent)
end
to process.sentence :sent
if emptyp :sent [output []]
output fput (process.word first :sent) ( bf :sent)
end
Program file for this chapter:
What’s wrong with this procedure?
If you said “It’s a recursive procedure without a stop rule,” you’ve solved a simple problem
in This branch of computer science is concerned with the
and the of programs.
The field is called analysis of rather than analysis of because
the emphasis is on the meaning of a program (how you might express the program in
English) and not on the details of its expression in a particular language. For example,
the error in the procedure
is just as fatal as the error in the first example, but there isn’t much of theoretical
interest to say about a misspelled procedure name. On the other hand, another branch
of computer science, is concerned with developing techniques to
ensure that a computer program really does correctly express the algorithm it is meant
to express.
The examples I’ve given so far are atypical, it’s worth noting, in that you were able to
see the errors in the procedures without having any real idea of what they do! Without
seeing you can tell that this program is doing something or other to
each word of a sentence, but you don’t know whether the words are being translated
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36

Partial preview of the text

Download 3 Algorithms and Data Structures and more Exams Data Structures and Algorithms in PDF only on Docsity!

process.snetence

algs

process.word

3 Algorithms and Data Structures

analysis of algorithms. correctness efficiency algorithms programs

program verification,

to process.sentence :sent output fput (process.word first :sent) (process.sentence bf :sent) end

to process.sentence :sent if emptyp :sent [output []] output fput (process.word first :sent) ( bf :sent) end

Program file for this chapter:

What’s wrong with this procedure?

If you said “It’s a recursive procedure without a stop rule,” you’ve solved a simple problem in This branch of computer science is concerned with the and the of programs.

The field is called analysis of rather than analysis of because the emphasis is on the meaning of a program (how you might express the program in English) and not on the details of its expression in a particular language. For example, the error in the procedure

is just as fatal as the error in the first example, but there isn’t much of theoretical interest to say about a misspelled procedure name. On the other hand, another branch of computer science, is concerned with developing techniques to ensure that a computer program really does correctly express the algorithm it is meant to express.

The examples I’ve given so far are atypical, it’s worth noting, in that you were able to see the errors in the procedures without having any real idea of what they do! Without seeing you can tell that this program is doing something or other to each word of a sentence, but you don’t know whether the words are being translated

2

2

Local Optimization vs. Efficient Algorithms

data structures,

not

order of growth,

quadratic formula

x

b b ac a x

ax bx c

108 Chapter 3 Algorithms and Data Structures

to quadratic :a :b :c localmake "x1 (-:b + sqrt (:b:b - 4:a:c))/2:a localmake "x2 (-:b - sqrt (:b:b - 4:a:c))/2:a print (sentence [The solutions are] :x1 "and :x2) end

to another language, converted from upper case to lower case letters, translated into a string of phoneme codes to be sent to a speech synthesizer, or what. (Even what I just said about doing something to the words of a sentence is an inference based on the names of procedures and variables, which might not really reflect the results of the program.) More interesting problems in analysis of algorithms have to do with the specific properties of particular algorithms.

In this chapter I discuss algorithms along with the different ways in which information can be represented in a computer program, because these two aspects of a program interact strongly. That is, the choices you make as a programmer about data representation have a profound effect on the algorithms you can use to solve your problem. Similarly, once you have chosen an algorithm, that choice determines the particular kinds of information your program will need to do its work. Algorithms and data structures are the central concerns of software engineering, the overall name for the study of how to turn a problem statement into a working program in a way that uses both the computer and the programming staff effectively.

When you’re trying to make a computer program run as fast as possible, the most obvious place to start is with the details of the instructions in the program. But that’s generally the most effective approach. Rethinking the big picture can give much more dramatic improvements. To show you what I mean, I’ll give some examples of both. Later I’ll talk about a more formal way to understand this same idea.

Consider the following procedure that implements the

This formula gives the two values of that solve the equation

    • = 0

2

local

n n n t nt nt n t

110 Chapter 3 Algorithms and Data Structures

quadratic

first butfirst fput last butlast lput fput

lput lput fput lput

fput lput

reverse reverse first fput

  • The actual time depends not only on what model of computer you have but also on how much memor y and what else is in it.

print cascade 1000 [lput # ?] []

print reverse cascade 1000 [fput # ?] []

to reverse :list if emptyp :list [output []] output lput first :list reverse bf :list end

Common subexpression elimination is an example of optimization. This means that we improved the program by paying attention to one small piece of it at a time. (A less elegant name for local optimization is “code bumming.”) Is it worth the effort? It depends how many times this procedure will be run. When I say that multiplication is slow, I mean that it takes a few millionths of a second. If you are writing a procedure to do the dozen problems in your high school algebra homework, the extra time you spend thinking up the second version and typing it into the editor probably outweighs the saving of time in running the procedure. But if you are trying to predict the weather and need to solve tens of thousands of equations, the saving may be significant.

If you want to write locally optimized Logo programs, it’s important to know that , , and take a constant amount of time regardless of the length of the input list, whereas , , and take an amount of time proportional to the length of the list. If you add items to a list, one by one, using , the length of time required is times the constant amount of time for each item. But if you add the same items using , if the first item takes microseconds, the last takes. On the average, each takes something like /2 microseconds, so the total time is /2. The gain in efficiency from using instead of isn’t significant if your list has only a few items, but the gain gets more and more significant as the size of the list increases. Suppose you want to create a list of the numbers from 1 to 1000. One straightforward way would be

On my home computer this instruction takes about 26 seconds.* If you just use in place of the list will come out in the wrong order, but it’s possible to reverse the order of that list to get the same result as the first version:

You might think this would be slower, because it has the extra step. But in fact this instruction took about 12 seconds. (It’s important that the tool in the Berkeley Logo library uses and to do its work. If we used the more obvious

6 2

4 2 10 2

6 6 3 2

4 1

4 3

4 2

6 1

lput cascade lput

lock

simplex

simp

lock 10 simplex 10 simp 10

global

recursive function

programming mathematics.

three

Local Optimization vs. Efficient Algorithms 111

then the elimination of in the template would be offset by the in the reversal.)

At the other extreme, the broadest possible optimization of a program is to think of an entirely new algorithm based on a different way of thinking about the original problem. As an example, in Chapter 2 there are three different programs to solve the Simplex lock problem. The first program, , works by enumerating explicitly all the different patterns of possible combinations. That algorithm is not fundamentally recursive; although my Logo implementation includes recursive subprocedures, the number of combinations for a five-button lock is not determined on the basis of the number for a four-button lock. (The program does compute the number of combinations that use four out of the five available buttons, but that isn’t the same thing.) The second program, , is based on a mathematical argument relating the number of combinations to a fairly simple —that is, a mathematical function with an inductive definition. Because the function is computationally simple, the intellectual energy I invested in doing the mathematics paid off with a significantly faster program. The third version, , uses a closed form formula that solves the problem in no time!

To illustrate more sharply the differences among these three programs, I tried each of them on a ten-button version of the Simplex lock. To compute took 260 seconds on my computer; took 80 seconds; and took less than half a second. For this size lock, understanding the mathematical idea of a recursive function sped up the program by a factor of three, and using the mathematical technique called generating functions achieved an additional speedup by a factor of almost 200! What’s important to understand about this example is that it wasn’t better skill that made the difference, but greater knowledge of (In the next section, though, you’ll learn a programming trick that can sometimes achieve similar speedups.)

Many “trick” math problems involve a similar shift in thinking about the fundamental algorithm to be used. For example, in Chapter 2 we computed the probability of picking a matching pair of socks out of a drawer containing six brown and four blue socks this way: pairs of 2 browns + pairs of 2 blues total pairs

Suppose we ask this question: Out of the same drawer of six browns and two blues, we pick socks at random; what is the probability that at least two of the socks match?

The number of triples of socks in which at least two are brown is the number in which all three are brown, ( ), plus the number in which two are brown and one is blue, ( ) ( ). The number in which at least two are blue is, similarly, ( ) + ( ) ( ). The

1 2

t 4 7

t

t 4 7

t 8 10 t 12 12

t

t

t

t t tt

t t^

t t t

t

t t^

t t t t tt

t t

t t

minutes seconds. hours

Memoization 113

to t :n :k localmake "result gprop :n :k if not emptyp :result [output :result] make "result realt :n :k pprop :n :k :result output :result end

to realt :n :k if equalp :k 0 [output 1] if equalp :n 0 [output 0] output (t :n :k-1)+(t :n-1 :k) end

What happens when we compute?

(3, 6) (3, 5)^

(3, 6) (3, 5)^

Many calculations are performed repeatedly. In the chart above I’ve underlined three places where (3, 5) is computed. Each of those in turn involves repeated computation of (3, 4) and so on. This computation took me about 18 seconds.

Here is a version of that uses property lists to remember all the values it’s already computed. This version will calculate (3, 5) only the first time it’s needed; a second request for (3, 5) will instantly output the remembered value.

Computing isn’t really a big enough problem to show off how much faster this version is; even the original program takes only 2 seconds on my home computer. But the amount of time needed grows quickly as you try larger inputs. Using the original procedure from Chapter 2, my computer took just under five to compute ; the program shown here took less than two This program computed in about three seconds; I estimate that the original procedure would take five to solve that problem! (As you can imagine, I didn’t try it.)

−

1

=

n

i

n i

[t 120 h 83]

t t 4 7 t 4 6 t 3 7

f n

n i

f i

f n n f i

f i

t h

114 Chapter 3 Algorithms and Data Structures

round ?1?

0 [1] [1 1] 1 [1 1] [1 2 1] 2 [3 1 1] [1 3 3 1] 3 [13 3 1 1] [1 4 6 4 1] 4 [75 13 3 1 1] [1 5 10 10 5 1] 5 [541 75 13 3 1 1] [1 6 15 20 15 6 1]

  • I’ve used property lists of numbers to hold the remembered values of the tfunction. If I wanted to use the same technique for some other function in the same workspace, I’d have to find a way to keep the values for the two functions from getting in each other’s way. For example, if and some other function , then I might store the value

on the appropriate property list.

The memoized version of has the same structure as the original. That is, in order to compute , the program must first carry out the two subtasks and. The only difference between the original version and the memoized version is that in the latter, whenever a second invocation is made with inputs that have already been seen, the result is output immediately without repeating that subtask. Any recursive function can be memoized in the same way.*

Sometimes, though, the same general idea—remembering the results of past computations—can be used more effectively by changing the program structure so that just the right subproblems are solved as they’re needed to work toward the overall solution. Rearranging the program structure isn’t called memoization, but we’re still using the same idea. For example, the Simplex lock function

from Chapter 2 is a combination (sorry about the pun) of values of two functions. It isn’t exactly helpful to remember every possible value of ( ) because each value is used only once. But the calculation of ( ) uses the entire th row of Pascal’s Triangle, and it’s easy to compute that if we remember the row above it. The values of ( ) are used repeatedly, so it makes sense to keep a list of them. So my plan is to have two lists, the first of which is a list of values of ( ) and the second a row of Pascal’s Triangle:

lessthanp

sort

show sort [5 20 3 5 18 9]

116 Chapter 3 Algorithms and Data Structures

to lessthanp :a :b if not namep "comparisons [make "comparisons 0] make "comparisons :comparisons+ output :a < :b end

to howmany print :comparisons ern "comparisons end

? [3 5 5 9 18 20]

The problem we want to solve is to take a list in unknown order and rearrange it to get a new list of the same members in some standard order. This might be alphabetical order if the members of the list are words, or size order if they’re numbers, or something else. For the most part, the exact ordering relation isn’t very important. As long as we have a way to compare two items and find out which comes first (or that they’re equal, sometimes) it doesn’t matter what the details of the comparison are. To make things simple, in this chapter I’ll assume we’re always sorting numbers.

Because the length of time per comparison depends on the nature of the things being compared, and because that length isn’t really part of what distinguishes one sorting algorithm from another, analyses of the time taken by a sorting program are usually expressed not in terms of seconds but in terms of number of comparisons. This measure also eliminates the effect of one computer being faster than another. To help make such measurements, we’ll compare two numbers using this procedure:

Of course, if we want to use or comparisons in a sorting algorithm, we should write analogous procedures for those. But in fact I’ll only need for the algorithms I’m going to show you. After trying out a sort program, we can find out how many comparisons it made using this convenient little tool:

After telling us the number of comparisons, this procedure erases the counter variable to prepare for the next experiment.

If you haven’t studied sort algorithms before, it will be a good exercise for you to invent one yourself before you continue. Your procedure should take a list of numbers as input, and should output a list of the same numbers in order from smallest to largest.

Sorting by Selection

unique

selection

Sorting by Selection 117

make "list cascade 100 [fput random 100 ?] []

[11 41 50 66 41 61 73 38 2 94 43 55 24 1 77 77 13 2 93 35 43 69 9 46 88 20 43 73 11 74 69 33 28 4 5 1 15 17 13 94 88 42 12 31 67 42 30 30 13 91 31 8 55 6 31 84 57 50 50 31 36 52 5 12 10 19 69 0 9 81 62 14 39 54 45 72 18 47 48 35 76 44 77 34 75 52 61 86 34 44 64 53 25 39 4 55 55 54 53 64]

Notice that it’s allowable for two (or more) equal numbers to appear in the input.

So that we can compare different algorithms fairly, we should try them on the same input data. You can make a list of 100 random numbers this way:

You should try out both your sort procedures and mine on your random list. In case you want to try your algorithm on my data, to compare the exact numbers of comparisons needed, here is the list I used:

Notice in passing that this is a list of 100 random numbers, but not a list of the first 100 numbers in random order. Some numbers, like 43, appear more than once in the list, while others don’t appear at all. This is perfectly realistic for numbers that occur in real life, although of course some situations give rise to lists of items.

Although there are many known sorting algorithms, most fall into two main groups. There are the ones that order the input items one at a time and there are the ones that divide the problem into roughly equal-sized smaller problems. I’ll show you one of each. Within a group, the differences between algorithms have to do with details of exactly how the problem is divided into pieces, what’s where in computer memory, and so on. But these details are generally much less important than the basic division between the two categories. If you took my advice and wrote your own sort procedure, and if you hadn’t studied sorting before, the one you wrote is almost certainly in the first category.

My sample algorithm in the first group is a sort. Expressed in words, the algorithm is this: First find the smallest number, then find the next smallest, and so on. This idea can be put in recursive form; the output from the procedure should be a list whose first member is the smallest number and whose remaining elements are the sorted version of the other numbers. I’ll show you two versions of this algorithm: first a straightforward but inefficient one, and then a version that’s improved in speed but not quite so obvious. Here’s the first version:

Sorting by Partition

ssort

ssort

ssort

first

isort

ssort

n n

n n

insertion sort,

Sorting by Partition 119

Suppose we try out on our list of 100 numbers. How many comparisons will be needed? To find the smallest of 100 numbers we have to make 99 comparisons; the smallest-so-far must be compared against each of the remaining ones. To find the next smallest requires 98 comparisons, and so on. Finally we have two numbers remaining to be sorted and it takes one comparison to get them in order. The total number of comparisons is 99 + 98 + 97 + + 2 + 1 = 4950

It makes no difference what order the numbers were in to begin with, or whether some of them are equal, or anything else about the input data. It takes 4950 comparisons for to sort 100 numbers, period. You can try out the program on various lists of 100 numbers to make sure I’m right.

In general, if we want to sort a list of length with the number of comparisons required is the sum of the integers from 1 to 1. It turns out that there is a closed form definition for this sum: ( 1) 2

Selection sort uses these three steps: Pull out the smallest value. Sort the other values. Put the smallest one at the front.

It’s the first of those steps that does the comparisons. A similar but different algorithm is which defers the comparisons until the last step: Pull out any old value (such as the ). Sort the other values. Put the chosen one where it belongs, in order.

Try writing a procedure to implement this algorithm. How many comparisons does it require? You’ll find that for this algorithm the answer depends on the input data. What is the smallest possible number of comparisons? The largest number? What kinds of input data give rise to these extreme values?

There is one fundamental insight behind all methods for sorting with fewer comparisons: Two small sorting jobs are faster than one large one. Specifically, suppose we have 100 numbers to sort. Using requires 4950 comparisons. Instead, suppose we split up

ssort

ssort

ssort

partition sort

120 Chapter 3 Algorithms and Data Structures

to psort :list if (count :list) < 2 [output :list] localmake "split guess.middle.value :list output sentence psort filter [? < :split] :list psort filter [not (? < :split)] :list end

to guess.middle.value :list output ((first :list) + (last :list)) / 2 end

the 100 numbers into two groups of 50. If we use on each group, each will require 1225 comparisons; the two groups together require twice that, or 2450 comparisons. That’s about half as many comparisons as the straight of 100 numbers.

But this calculation underestimates how much time we can save using this insight, because the same reasoning applies to each of those groups of 50. We can split each into two groups of 25. Then how many comparisons will be required altogether?

The basic idea we’ll use is to pick some number that we think is likely to be a median value for the entire list; that is, we’d like half the numbers to be less than this partition value and half to be greater. There are many possible ways to choose this partition value; I’m going to take the average of the first and last numbers of the (not yet sorted!) input. Then we run through the input list, dividing it into two smaller pieces by comparing each number against the partition value. (Notice that compares pairs of numbers within the input list; the partition sort compares one number from the list against another number that might or might not itself be in the list.) We use the same technique recursively to sort each of the two sublists, then append the results.

Note the similarities and differences between this selection sort algorithm: Pull out the smallest value. Sort the other values. Put the smallest one at the front.

and the following algorithm:

Divide the input into the small-value half and the large-value half. Sort each half separately. Put the sorted small values in front of the sorted large ones.

Again, I’ll write this program more than once, first in an overly simple version and then more realistically. Here’s the simple one:

show psort [4 4 4 4 4]

psort psort psort

psort ssort psort

high

high

quite

so all

122 Chapter 3 Algorithms and Data Structures

to psort1 :split :in :low :high if emptyp :in [output sentence (psort :low) (psort :high)] if lessthanp first :in :split ~ [output psort1 :split (butfirst :in) (fput first :in :low) :high] output psort1 :split (butfirst :in) :low (fput first :in :high) end

?

This version of has one good attribute and one bad attribute. The good attribute is that it’s very cleanly organized. You can see that it’s the job of to choose the partition value and the job of to divide the list in two parts based on comparisons with that value. The bad attribute is that it doesn’t work as it stands.

As for any recursive procedure, it’s important that the input get smaller for each recursive invocation. If not, could end up invoking itself over and over with the same input. It’s very easy to see that avoids that danger, because the input list is shorter by exactly one member for each recursive invocation. But divides its input into two pieces, each of which ought to be about half the length of the original if we’re lucky. We’re lucky if the partition value we choose is, in fact, the median value of the input list. If we’re less lucky, the two parts might be imbalanced, say 1/4 of the members below the partition and 3/4 of them above it. Can we be unlucky that of the input numbers are on the same side of the partition? See if you can think of a case in which this will happen.

The partition value is chosen as the average of two members of the input list. If those two members (the first and last) are unequal, then one of them must be less than the partition value and the other greater. So there will be at least one number on each side of the partition. But if the two averaged numbers are equal, then the partition value will be equal to both of them. Each of them will be put in the bucket. If all the other numbers in the list are also greater than or equal to the partition, then they’ll all end up in the bucket, and nothing will be accomplished in the recursion step. The simplest failing example is trying to sort a list of numbers all of which are equal, like

We could take various approaches to eliminating this bug. See how many ways you can think of, and decide which you like best, before reading further.

Since the problem has to do with the choice of partition value, you could imagine using a more complicated means to select that value. For example, you could start with the first member of the input list, then look through the list for another member not equal to the first. When you find one, average the two of them and that’s the partition value. If you get all the way to the end of the list without finding two unequal members,

three

Sorting by Partition 123

low high equal equal

lessthanp

equaltop lessthanp

lessthanp psort psort low

if equalp first :list last :list [...]

if lessthanp first :in :split [...] if equaltop first :in :split [...]

to psort :list if emptyp :list [output []] if emptyp butfirst :list [output :list] localmake "split ((first :list) + (last :list)) / 2 if lessthanp first :list :split ~ [output psort1 :split (butfirst :list) (list first :list) []] output psort1 :split (butlast :list) (list last :list) [] end

declare the list sorted and output it as is. The trouble with this technique is that many extra comparisons are needed to find the partition value. Those comparisons don’t really help in ordering the input, but they do add to the time taken just as much as the “real” comparisons done later.

Another approach is to say that since the problem only arises if the first and last input members are equal, we should treat that situation as a special case. That is, we’ll add an instruction like

Again, this approach adds a comparison that doesn’t really help to sort the file, although it’s better than the first idea because it only adds one extra comparison per invocation instead of perhaps several.

A more straightforward approach that might seem to make the program more efficient, rather than less, is to divide the list into buckets, , , and. This way, the problem gets shorter faster, since the bucket doesn’t have to be sorted recursively; it’s already in order. The trouble is that it takes two comparisons, one for equality and one for , to know how to direct each list member into a three-way split. Some computers can compare numbers once and branch in different directions for less, equal, or greater; one programming language, Fortran, includes that kind of three-way branching through an “arithmetic IF” statement that accepts different instructions for the cases of a given quantity being less than, equal to, or greater than zero. But in Logo we’d have to say

with two comparisons for each list member. (I’m imagining that would keep track of the number of comparisons just as does.)

What I chose was to do the first test for the list in instead of , and use it to ensure that either the first or the last member of the list starts out the bucket.

worse

more

Sorting by Partition 125

make "bad cascade 100 [fput 20 ?] []

make "inorder cascade 100 [lput # ?] []

psort

Psort Psort

Psort ssort

reverse psort

:inorder

psort

psort

:inorder

psort

Now try some experiments. Try on your random list, then try to find input lists that give the best and worst possible results.

required 725 comparisons for my random list. That’s somewhat more than we predicted for the best case, but not too much more. seems to have done pretty well with this list. The simplest worst-case input is one in which all the numbers are the same; I said

to make such a list. required 5049 comparisons to sort this list, slightly than at 4950 comparisons.

What would a best-case input look like? It would divide evenly at each stage; that is, the median value at each stage would be the average of the first and last values. The simplest list that should meet that criterion is a list of all the numbers from 1 to 100 in order:

(Or you could use the trick discussed earlier, but for only 100 numbers it didn’t seem worth the extra typing to me.) Using to sort this list should require, we said, somewhere around 650 to 700 comparisons. In fact it took 734 comparisons when I tried it, slightly than my randomly ordered list (725 comparisons).

Even 734 comparisons isn’t terrible by any means, but when an algorithm performs worse than expected, a true algorithm lover wants to know why. Test cases like these can uncover either inefficiencies in the fundamental algorithm or else ways in which the actual computer program doesn’t live up to the algorithm as described in theoretical language. If we could “tune up” this program to sort in fewer than 700 comparisons, the change might well improve the program’s performance for any input. See if you can figure out what the problem is before reading further. You can try having print out its inputs each time it’s called, as a way to help gather information.

Here’s a very large hint. I tried using the original version of , before fixing the bug about the recursion sometimes leaving all the numbers in one basket, and it sorted in only 672 comparisons. (I knew the bug wouldn’t make trouble in this case because none of the numbers in this particular input list are equal.) Can you devise a better that both works all the time and performs optimally for the best-case input?

This partition sorting scheme is essentially similar to a very well-known algorithm named quicksort, invented by C. A. R. Hoare. Quicksort includes many improvements over this algorithm, not primarily in reducing the number of comparisons but in

Order of Growth

ssort

ssort psort

psort ssort

mergesort:

Merge

126 Chapter 3 Algorithms and Data Structures

decreasing the overhead time by, for example, exchanging pairs of input items in their original memory locations instead of making copies of sublists. Quicksort also switches to a more straightforward -like algorithm for very small input lists, because the benefit of halving the problem is outweighed by the greater complexity. (In fact, for a two-item input, makes one comparison and two.)

Here’s the partition sort algorithm again: Divide the input into the small-value half and the large-value half. Sort each half separately. Put the sorted small values in front of the sorted large ones.

The idea of cutting the problem in half is also used in the following algorithm, called

Divide the input arbitrarily into two equal size pieces. Sort each half separately. the two sorted pieces by comparing values.

In a way, mergesort is to partition sort as insertion sort is to selection sort. Both insertion sort and mergesort defer the comparisons of numbers until the final step of the algorithm.

There is one important way in which mergesort is better than partition sort. Since mergesort doesn’t care how the input values are separated, we can ensure that the two pieces are each exactly half the size of the input. Therefore, the number of comparisons needed is always as small as possible; there are no bad inputs. Nevertheless, quicksort is more widely used than mergesort, because the very best implementations of quicksort seem to require less overhead time, for the average input, than the best implementations of mergesort.

If you want to write a mergesort program, the easiest way to divide a list into two equal pieces is to select every other member, so the odd-position members are in one half and the even-position members in the other half.

I’ve mentioned that the complete quicksort algorithm includes several optimization strategies to improve upon the partition sort I’ve presented here. How important are these strategies? How much does overhead contribute to the cost of a program? I did some experiments to investigate this question.

First I timed and with inputs of length 300. Here are the results: