1
Chapter 7: Sorting (Quicksort) CE 221 Data Structures and Algorithms
Izmir University of Economics
Data Structures and Algorithms Chapter 7: Sorting (Quicksort) Text: - - PowerPoint PPT Presentation
CE 221 Data Structures and Algorithms Chapter 7: Sorting (Quicksort) Text: Read Weiss, 7.7 Izmir University of Economics 1 Quicksort As the name implies quicksort is the fastest known sorting algorithm in practice. Average running
1
Izmir University of Economics
2
Izmir University of Economics
3
Izmir University of Economics
4
Izmir University of Economics
5
Izmir University of Economics
6
Izmir University of Economics
left center right
left pivot center right
left center pivot right
7
Izmir University of Economics
elements to the right part. Small and large are with respect to the pivot.
than the pivot. We move j left, skipping over elements that are larger than the pivot.
i j
i j
8 Izmir University of Economics
After first swap After second swap
i j
i j
i j
9
Izmir University of Economics
Before third swap After swap with the pivot IMPORTANT: In case of equality both i and j will stop.
j i
10
Izmir University of Economics
11
Izmir University of Economics public static <AnyType> void swapReferences(AnyType [] a, int index1, int index2) { AnyType tmp = a[ index1 ]; a[ index1 ] = a[ index2 ]; a[ index2 ] = tmp; }
12 Izmir University of Economics
13 Izmir University of Economics
This is not correct
i = left + 1, j = right - 2; for( ; ; ) { while( a[ i ].compareTo(pivot) < 0 ) i++; while( a[ j ].compareTo(pivot) > 0 ) j--; if( i < j ) swapReferences( a, i, j ); else break; }
Izmir University of Economics 14
N i
i
2 Izmir University of Economics 15
Izmir University of Economics 16
Izmir University of Economics
) 2 ( ) 1 ( ) ( 2 ) 1 ( ) 1 ( ) 1 ( ) ( 2 ) ( ) 1 ( ) ( 1 ) (
2 2 2 1 1
N c i T N T N cN i T N NT cN i N T i T N N T
N i N i N i
cN N T N N NT c cN N T N T N N NT 2 ) 1 ( ) 1 ( ) ( 2 ) 1 ( 2 ) 1 ( ) 1 ( ) ( 1 2 ) 1 ( 1 ) ( N c N N T N N T
3 2 2 ) 1 ( 3 ) 2 ( 1 2 2 ) 3 ( 1 ) 2 ( 2 1 ) 2 ( ) 1 ( 1 2 ) 1 ( 1 ) ( c T T N c N N T N N T N c N N T N N T N c N N T N N T ) log ( ) ( ) 2 3 ) 1 ( (log 2 2 ) 1 ( 1 ) ( 1 2 2 ) 1 ( 1 ) (
1 3
N N O N T N c T N N T i c T N N T
e N i
17
Izmir University of Economics 18