Previous Lecture lect13 Next Lecture

Relevant topics in the textbook:

Data Structures and Other Objects Using C++ Chapter 13.2

Notation:

Infix

Prefix (“Polish notation”)

Postfix (“Reverse Polish notation”)

Divide and conquer

Divide and conquer sorting algorithms

Mergesort

Mergesort Analysis

Quicksort

Quicksort Algorithm

// Makefile
add quicksort.o to dependencies
// quicksort.h

class Quicksort{
	public:
		void printArray(const int a[], size_t size);
		void partition(int a[], size_t size, size_t& pivotIndex);
		void sort(int a[], size_t size);
};
// quicksort.cpp

#include<iostream>
#include "quicksort.h"

using namespace std;

void Quicksort::printArray(const int a[], size_t size) {
	cout << "Printing Array" << endl;
	for (int i = 0; i < size; i++) {
		cout << "a[" << i << "] = " << a[i] << endl;
	}
}

void Quicksort::partition(int a[], size_t size, size_t& pivotIndex) {
	int pivot = a[0];		 // choose 1st value for pivot
	size_t left = 1;		 // index just right of pivot
	size_t right = size - 1; // last item in array
	int temp;
	cout << endl <<"Chose a pivot: " << pivot << endl;
	printArray(a, size);
	while (left <= right) {
		// increment left if <= pivot
		while (left < size && a[left] <= pivot) {
			left++;
		}

		// decrement right if > pivot
		while (a[right] > pivot) {
			right--;
		}

		// swap left and right if left < right
		if (left < right) {
			cout << "Swapping: " << a[left] << " with " << a[right] << endl;
			temp = a[left];
			a[left] = a[right];
			a[right] = temp;
			printArray(a, size);
		}
	}
	cout << "Swapping pivot: " << a[0] << " with " << a[right] << endl;
	// swap pivot with a[right]
	pivotIndex = right;
	temp = a[0];
	a[0] = a[pivotIndex];
	a[pivotIndex] = temp;
	printArray(a, size);
}

void Quicksort::sort(int a[], size_t size) {
	size_t pivotIndex;		// index of pivot
	size_t leftSize;		// num elements left of pivot
	size_t rightSize;		// num elements right of pivot
	
	

	if (size > 1) {
		// partition a[] based on pivotIndex
		partition(a, size, pivotIndex);

		// Compute the sizes of left and right sub arrays
		leftSize = pivotIndex;
		rightSize = size - leftSize - 1;

		// recursive call sorting the left array
		sort(a, leftSize);

		// recursive call sorting the right array
		sort((a + pivotIndex + 1), rightSize);
	}
}
// add to main.cpp
#include "quicksort.h"

Quicksort Analysis