Transcript file
QUICK SORT
QUICK SORT IS AWESOME
•
Fast sorting algorithm
•
Can be used to sort big data volumes
•
Uses a divide and conquer strategy that can be multithreaded
•
It’s a top 10 algorithm for the 20 th Century**
(**http://www.uta.edu/faculty/rcli/TopTen/topten.pdf)
•
And it does all this with in-place sorting – needing no additional storage!
HOW DOES IT WORK
1. Choose a pivot value
2. Partition values with less values on one side of pivot and greater on the other
3. Sort remainder block recursively using the above steps
BIG O FOR QUICKSORT
•
On Average, the algorithm takes O(n log n) comparisons to sort n items.
•
In the worst case, it makes O(n^2) comparisons.
•
Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort
at the opposite end
•
Quicksort is a conquer-then-divide algorithm, which does most of the work during the
partitioning and the recursive calls. The subsequent reassembly of the sorted partitions
involves trivial effort.
•
Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by
splitting the input array in half. Most of the work happens during the recursive calls and
the merge phase.
O(N LOG N)
QUICK SORT IN ACTION
QUICKSORT CODE
Quicksort(A as array, low as int, high as int)
{
if (low < high){
pivot_location = Partition(A,low,high)
Quicksort(A,low, pivot_location - 1)
Quicksort(A, pivot_location + 1, high)
}
}
Partition(A as array, low as int, high as int)
{
pivot = A[low]
leftwall = low
for i = low + 1 to high {
if (A[i] < pivot) then{
leftwall = leftwall + 1
swap(A[i], A[leftwall])
}
}
swap(A[low],A[leftwall])
return (leftwall)
}
public class MyQuickSort {
private int array[];
private int length;
public void sort(int[] inputArr) {
if (inputArr == null || inputArr.length == 0) { return; }
this.array = inputArr;
length = inputArr.length;
quickSort(0, length - 1);
}
private void exchangeNumbers(int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
private void quickSort(int lowerIndex, int higherIndex) {
int i = lowerIndex;
int j = higherIndex;
// calculate pivot number, I am taking pivot as middle index number
int pivot = array[lowerIndex+(higherIndex-lowerIndex)/2];
// Divide into two arrays
while (i <= j) {
while (array[i] < pivot) { i++; }
while (array[j] > pivot) { j--; }
if (i <= j) {
exchangeNumbers(i, j);
//move index to next position on both sides
i++; j--;
}
}
// call quickSort() method recursively
if (lowerIndex < j) { quickSort(lowerIndex, j); }
if (i < higherIndex) { quickSort(i, higherIndex); }
}
Questions?
WORK CITED
•
http://www.algolist.net/
•
en.wikipedia.org/wiki/
•
CS150: Quick Sort in Action; https://www.youtube.com/watch?v=aQiWF4E8flQ
•
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
QUICK SORT
BY PATRIK WILLIAMS, VIMAL DARJI, GARY
HAYE, ROSIE CUMBERBATCH
ITEC 2150 Section 04
Spring 2015
05/07/2015
Dr. Brannock