Quicksort 4-18-2013 - Clarkson Universityjsearlem/cs142/sp13/slides/24.qsort.pdf · Sorting...

Post on 25-May-2020

2 views 0 download

transcript

Quicksort

4-18-2013

Thursday, April 18th Barben Rooms A&B, Cheel

4:00 pm–4:45 pm Panel discussion on “Technical Career Opportunities”, Moderated by Bob Lockwood ‘86

5:00 pm–5:45 pm Roundtables:

How to Communicate with your Client – Differences in Internal vs. External Client Development with Chris Snelling ‘86 and Rich Bogart ‘86

Technology Trends in Industry with Ron Ayers ‘02 and Chris Fohlin ‘07

Tricks and Tips for the Job Seeker with Dan Dedrick ‘06 and Bob Lockwood ‘86

6:00 pm – 6:45 pm “Building Your Digital Presence”; Presentation by Chris Fohlin ’07

Employers and clients do their homework on you before you walk through the door. Does your online presence paint the right picture? Learn best practices for managing, and maximizing, your professional digital image.

)

Sorting

Quicksort

OOP

inheritance

Reading: Maciel

Chapter 15, Sorting

Project#2: Evil Hangman, due Wed. 4/24

see the sample output

Selection Sort ϴ(n2)

if ( [start,stop) contains more than one element ) {

i_max = index of the largest element in [start,stop)

swap a[i_max] and a[stop - 1]

sort [start, stop-1)

}

Insertion Sort ϴ(n2)

if ( [start,stop) contains more than one element ) {

sort [start, stop-1)

insert a[stop-1] into [start, stop-1)

}

Mergesort

if ( the array contains more than one element ) {

sort the first half of the array

sort the second half of the array

merge the two sorted halves

}

Quicksort

find a “pivot point”

partition around the pivot

sort halves

example run: (top level of recursion)

[ 60 12 37 42 25 38 16 ]

[ 60 12 37 42 ] [ 25 38 16 ] 1. divide in half

[ 12 37 42 60 ] [ 16 25 38 ] 2. sort halves

[ 12 16 25 37 38 42 60 ] 3. merge

example run: trace

[ 60 12 37 42 25 38 16 ]

[ 60 12 37 42 ] [ 25 38 16 ]

[ 60 12 ] [ 37 42 ] [ 25 38 ] [ 16 ]

[ 60 ] [ 12 ] [ 37 ] [ 42 ] [ 25 ] [ 38 ] [ 16 ]

[ 12 60 ] [ 37 42 ] [ 25 38 ] [ 16 ]

[ 12 37 42 60 ] [ 16 25 38 ]

[ 12 16 25 37 38 42 60 ]

merging algorithm: array [ 60 12 37 42 25 38 16]

first second result

[ 12 37 42 60 ] [ 16 25 38 ] [ ]

[ 37 42 60 ] [ 16 25 38 ] [ 12 ]

[ 37 42 60 ] [ 25 38 ] [ 12 16 ]

[ 37 42 60 ] [ 38 ] [ 12 16 25 ]

[ 42 60 ] [ 38 ] [ 12 16 25 37 ]

[ 42 60 ] [ ] [ 12 16 25 37 38 ]

[ ] [ ] [ 12 16 25 37 38 42 60 ]

idea:

find a “pivot point”

partition around the pivot

sort halves

}

if ( the array contains more than one element ) {

choose a pivot element

partition the array around the pivot

sort each subarray

}

Partition must rearrange the array so that the following 3 conditions hold:

1. the element a[p] is in its final place in the array, for some p

2. all elements in a[first..p-1] are ≤ a[p]

3. all elements in a[p+1..last] are ≥ a[p]

example: [ 30 10 14 37 42 13 51 5 30 ]

pivot

1. select a pivot

2. partition around the pivot

[ 10 14 13 5 | 30 | 37 42 51 30 ]

3. sort the partitions

[ 5 10 13 14 30 30 37 42 51 ]

If the pivot point divides the list exactly in half, then the number of comparisons would be N log N

If the pivot point is chosen so that one partition is always empty, then the running time is N2

The performance of quicksort heavily depends on the pivot point

best case: pivot element is the median value in the array (divides the array in half)

worst case: the first element of the array is chosen to be the pivot point, but the array is already sorted

in practice, large parts of an input array can be already in sorted order

choose a random element to be the pivot (but then need a call to a pseudorandom number generator)

compromise: choose the median of the first, middle and last element of the array

example: [ 60 12 37 42 25 38 16 ]

pivot

1. select a pivot: median of [16 42 60] => 42

2. partition around the pivot

[ 12 37 25 38 16 ] 42 [ 60 ]

2. sort the partitions

[ 12 16 25 37 38 42 60 ]

[ 60 12 37 42 25 38 16 ]

[ 12 37 25 38 16 ] 42 [ 60 ]

[ 12 ] 16 [ 37 25 38 ] 42 [ 60 ]

[ 12 ] 16 [ 25 ] 37 [ 38 ] 42 [ 60 ]

[ 12 ] 16 [ 25 37 38 ] 42 [ 60 ]

[12 16 25 37 38 ] 42 [ 60 ]

[12 16 25 37 38 42 ] [ 60 ]

[ 12 16 25 37 38 42 60 ]

Quicksort

worst case: ϴ(n2)

best & average case: ϴ(n log n)

easy to write recursively

Mergesort

all cases: ϴ(n log n)

disadvantage: needs extra space proportional to n

good when sequential access is required (e.g. sort a linked list)

easy to write recursively

use a better partitioning element (pivot) to avoid the worst case

median-of-3 partitioning works well in practice

use a simple sort for small partitions (can reduce running time by 20%)

e.g. if size of array ≤ M then use insertion sort

The C++ standard library (in <algorithm>) provides the following functions: template<typename RI>

void sort(RI first, RI last);

template<typename RI, typename Compare>

void sort(RI first, RI last, Compare comp);

The template parameter RI is a random-access iterator.

The data to be sorted is in the range first .. last, where last is one past the last data value.

In practice you would tend to use these

Assume that array items contains 16 integers.

sort(items, items + 16);

● will sort the whole array.

sort(items, items + 8);

● will sort the first half.

sort(items, items + 16, greater<int>()); ● will sort in descending order.

Assume that v is a vector.

sort(v.begin(), v.end()); // sorts vector v

Objects, classes, and inheritance, plus

An object is a software entity that combines state and

behavior.

A class describes the state (member data) and services

(member functions) provided by objects that are

instances of that class.

Classes can be related by inheritance.

polymorphism and dynamic binding.

Goals of OO: abstraction, encapsulation,

comprehensibility, changeability, and reusability.

We’ve now looked at classes and objects.

What about inheritance, polymorphism and dynamic binding?

Object-oriented programming (OOP) is popular because:

It enables reuse of previous code saved as classes

Inheritance and hierarchical organization capture idea:

One thing is a refinement or extension of another

UML Class Diagram

class Arrow : public Line {...}

An Arrow “is a” Line

Arrow

IS-A (inheritance)

Line

important to

make this public

class Line {...}

FilledCircle Line Point

HAS-A

(composition)

2

UML Class Diagram

class Line {

private:

Point endpt1, endpt2;

A Line “has a” Point

Circle

FilledCircle

Point

IS-A (inheritance)

HAS-A

(composition)

1

base class or superclass

derived class or subclass

Confusing has-a and is-a leads to misusing inheritance

Model a has-a relationship with an attribute (data member/instance variable)

class C { ... private: B part; ...}

Model an is-a relationship with inheritance

If every C is-a B then model C as a derived class (also called subclass) of B

Show this: in C include : public B:

class C : public B { ... }

/** the Point class represents a 2D point */

class Point {

private:

int xcoord, ycoord;

public:

Point() : xcoord(0), ycoord(0) {}

Point(int newx, int newy) : xcoord(newx), ycoord(newy) {}

int getX() { return xcoord; }

int getY() { return ycoord; }

void display();

};

class Circle {

private:

Point center;

float radius:

public:

Circle(): center(Point()), radius(1.0f) {}

Circle(int x, int y, float newradius)

: center(Point(x,y)), radius(newradius) {}

float getRadius() { return radius; }

double computeArea();

void display();

};

class FilledCircle public Circle {

private:

string color;

public:

FilledCircle(): Circle(), color(“black”) {}

FilledCircle(int x, int y, float newradius, string newcolor)

: Circle(x, y, newradius), color(newcolor) {}

};

/** test program for shapes */

int main() {

/* Test the Point class, starting with constructors & accessors: */

Point p1;

Point p2(100, 200);

Point p3(50, 50);

cout << "Point 1: " << p1.getX() << ":" << p1.getY() << endl;

cout << "Point 2: " << p2.getX() << ":" << p2.getY() << endl;

cout << "Point 3: " << p3.getX() << ":" << p3.getY() << endl;

/* test Point's display method */

p2.display();

/* Next test the Circle class, starting with constructors: */

/* (continued on next slide) */

/* test program for shapes, continued */

Circle c1(100, 40, 2.5f);

Circle c2;

/* test Circle's accessors and method computeArea */

cout << "Circle c1 radius: " << c1.getRadius() << endl;

cout << “Area of circle c1 is: " << c1.computeArea() << endl;

/* test Circle's display method */

c1.display();

/* Test the FilledCircle class, starting with the constructors */

FilledCircle fc3;

FilledCircle fc4(20, 30, 2.5f, "red");

/* continued on next slide */

/* test program for shapes, continued */

/* Test the FilledCircle class, starting with the constructors */

FilledCircle fc3;

FilledCircle fc4(20, 30, 2.5f, "red");

/* Test the accessors and inherited method computeArea */

cout << "Filled Circle fc3 color is " << fc3.getColor() << endl;

cout << "fc3 area: " << fc3.computeArea() << endl;

cout << "Filled Circle fc4 color is " << fc4.getColor() << endl;

/* Test the FilledCircle's display method */

fc4.display();

/* Testing completed */

return 0;

}

Sorting

Maciel: Chapter 15

Software Life Cycle

Maciel: Chapter 11

Error Checking

Maciel, Chapter 4