Docsity

Sorting Algorithms: Understanding the Complexity and Efficiency, Slides of Data Representation and Algorithm Design

Toggle sidebar
bg1
3.5 Applications
2
obvious applications
problems become easy once
items are in sorted order
non-obvious applications
Sorting Applications
Applications.
!Sort a list of names.
!Organize an MP3 library.
!Display Google PageRank results.
!List RSS news items in reverse chronological order.
!Find the median.
!Find the closest pair.
!Binary search in a database.
!Identify statistical outliers.
!Find duplicates in a mailing list.
!Data compression.
!Computer graphics.
!Computational biology.
!Supply chain management.
!Book recommendations on Amazon.
!Load balancing on a parallel computer.
. . .
3
Engineering a System Sort
Bentley-McIlroy. [Engineeering a Sort Function]
!Original motivation: improve qsort() function in C.
!Basic algorithm = 3-way quicksort with cutoff to insertion sort..
!Partition on Tukey's ninther: median-of-3 elements, each of which
is a median-of-3 elements.
RAMGX JKB E
A MR X KG J EB
K EM
Kninther
medians
groups of 3
nine evenly spaced elements
approximate median-of-9
4
Java System Sorts
Java's system sort.
!Can sort array of type Comparable or any primitive type.
!Uses Bentley-McIlroy quicksort for primitive types.
!Uses mergesort for objects.
Q. Why difference between objects and primitive types?
import java.util.Arrays;
public class IntegerSort {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
int[] a = new int[N];
for (int i = 0; i < N; i++)
a[i] = StdIn.readInt();
Arrays.sort(a);
for (int i = 0; i < N; i++)
System.out.println(a[i]);
}
}
docsity.com
pf3
pf4
pf5

Partial preview of the text

Download Sorting Algorithms: Understanding the Complexity and Efficiency and more Slides Data Representation and Algorithm Design in PDF only on Docsity!

3.5 Applications

2 obvious applications problems become easy once items are in sorted order non-obvious applications

Sorting Applications

Applications.

! Sort a list of names. ! Organize an MP 3 library. ! Display Google PageRank results. ! List RSS news items in reverse chronological order. ! Find the median. ! Find the closest pair. ! Binary search in a database. ! Identify statistical outliers. ! Find duplicates in a mailing list. ! Data compression. ! Computer graphics. ! Computational biology. ! Supply chain management. ! Book recommendations on Amazon. ! Load balancing on a parallel computer.

... 3

Engineering a System Sort

Bentley-McIlroy. [Engineeering a Sort Function]

! Original motivation: improve qsort() function in C.

! Basic algorithm = 3-way quicksort with cutoff to insertion sort..

! Partition on Tukey's ninther: median-of-3 elements, each of which

is a median-of-3 elements.

R A M G X K B J E R A M G X K B J E M K E K ninther medians groups of 3 nine evenly spaced elements approximate median-of- 4

Java System Sorts

Java's system sort.

! Can sort array of type Comparable or any primitive type.

! Uses Bentley-McIlroy quicksort for primitive types.

! Uses mergesort for objects.

Q. Why difference between objects and primitive types?

import java.util.Arrays; public class IntegerSort { public static void main(String[] args) { int N = Integer.parseInt(args[ 0 ]); int[] a = new int[N]; for (int i = 0 ; i < N; i++) a[i] = StdIn.readInt(); Arrays.sort(a); for (int i = 0 ; i < N; i++) System.out.println(a[i]); } }

5

Breaking Java's System Sort

Is it possible to make system sort go quadratic?

! No, for mergesort.

! Yes, for deterministic quicksort.

McIlroy's devious idea. [A Killer Adversary for Quicksort]

! Construct malicious input while running system quicksort,

in response to elements compared.

! If p is pivot, commit to (x < p) and (y < p), but don't commit to

(x < y) or (x > y) until x and y are compared.

Consequences.

! Confirms theoretical possibility.

! Algorithmic complexity attack: you enter linear amount of data;

server performs quadratic amount of work.

so, why are most system implementations of quicksort deterministic? 6

Breaking Java's System Sort

A killer input. Blows function call stack in Java and crashes program.

% more 250000 .txt 0 218750 222662 11 166672 247070 83339 156253 ... % java IntegerSort < 250000 .txt Exception in thread "main" java.lang.StackOverflowError at java.util.Arrays.sort 1 (Arrays.java: 562 ) at java.util.Arrays.sort 1 (Arrays.java: 606 ) at java.util.Arrays.sort 1 (Arrays.java: 608 ) at java.util.Arrays.sort 1 (Arrays.java: 608 ) at java.util.Arrays.sort 1 (Arrays.java: 608 )

... Java's sorting library crashes, even if you give it as much stack space as Windows allows. 250,000 integers between 0 and 250, more disastrous possibilities in C 7

Natural Order

public class Date implements Comparable { private int month, day, year; public Date(int m, int d, int y) { month = m; day = d; year = y; } public int compareTo(Date b) { Date a = this; if (a.year < b.year ) return - 1 ; if (a.year > b.year ) return + 1 ; if (a.month < b.month) return - 1 ; if (a.month > b.month) return + 1 ; if (a.day < b.day ) return - 1 ; if (a.day > b.day ) return + 1 ; return 0 ; } } only compare dates to other dates 8

Sorting Different Types of Data

Goal. Sort objects with no natural order or with a different orders.

Ex. Sort strings by:

! Natural order. Now is the time

! Case insensitive. is Now the time

! French. real réal rico

! Spanish. café cuidado champiñón dulce

String[] a; ... Arrays.sort(a); Arrays.sort(a, String.CASE_INSENSITIVE_ORDER); Arrays.sort(a, Collator.getInstance(Locale.FRENCH)); Arrays.sort(a, Collator.getInstance(Locale.SPANISH)); ch and rr are single letters import java.text.Collator;

13

Stability

A stable sort preserves the relative order of records with equal keys.

@#%&@!! Students in section 3 no longer in order by name.

Andrews Battle Chen Fox Furia Gazsi Kanaga Rohde 3 4 2 1 3 4 3 3 A C A A A B B A 664 - 480 - 0023 874 - 088 - 1212 991 - 878 - 4944 884 - 232 - 5341 766 - 093 - 9873 665 - 303 - 0266 898 - 122 - 9643 232 - 343 - 5555 097 Little 121 Whitman 308 Blair 11 Dickinson 101 Brown 22 Brown 22 Brown 343 Forbes Andrews Battle Chen Fox Furia Gazsi Kanaga Rohde 3 4 2 1 3 4 3 3 A C A A A B B A 664 - 480 - 0023 874 - 088 - 1212 991 - 878 - 4944 884 - 232 - 5341 766 - 093 - 9873 665 - 303 - 0266 898 - 122 - 9643 232 - 343 - 5555 097 Little 121 Whitman 308 Blair 11 Dickinson 101 Brown 22 Brown 22 Brown 343 Forbes sort by name then sort by section 14

Stability

Q. Which sorts are stable?

! Selection sort.

! Insertion sort.

! Quicksort.

! Mergesort.

Annoying fact. Many useful sorting algorithms are unstable.

15

Lots of Sorting Algorithms

Internal sorts.

! Insertion sort, selection sort, bubblesort, shaker sort.

! Quicksort, mergesort, heapsort, samplesort, introsort, shellsort.

! Solitaire sort, red-black sort, splaysort, Dobosiewicz sort, psort, ...

External sorts. Poly-phase mergesort, cascade-merge, oscillating sort.

Radix sorts.

! Distribution, MSD, LSD.

! 3-way radix quicksort.

Parallel sorts.

! Bitonic sort, Batcher even-odd sort.

! Smooth sort, cube sort, column sort.

! GPUsort.

16

Lots of Sorting Attributes

Q. Isn't the system sort good enough.

A. Maybe.

! Stable?

! Multiple keys?

! Deterministic?

! Keys all distinct?

! Multiple key types?

! Linked list or arrays?

! Large or small records?

! Is your file randomly ordered?

! Need guaranteed performance?

A. An elementary sorting algorithm may be the method of choice.

A. Use well understood topic to study basic issues.

many more combinations of attributes than algorithms

3.6 Complexity

18

Computational Complexity

Computational complexity. Framework to study efficiency of

algorithms for solving a particular problem X.

Machine model. Count fundamental operations.

Upper bound. Cost guarantee provided by some algorithm for X.

Lower bound. Proven limit on cost guarantee of any algorithm for X.

Optimal algorithm. Algorithm with best cost guarantee for X.

Ex: sorting.

! Machine model = # comparisons in decision tree.

! Upper bound = N log 2 N from mergesort.

! Lower bound = N log 2 N - N log 2 e.

! Optimal algorithm = mergesort.

lower bound! upper bound access information only through compares 19

Decision Tree

a b c b < c yes (^) no b < c yes no a < c yes no a < c yes no a c b c a b b a c b c a c b a a < b yes no code between comparisons (e.g., sequence of exchanges) 20

Comparison Based Sorting Lower Bound

Theorem. Any comparison based sorting algorithm must use

"(N log 2 N) comparisons.

Pf.

! Suffices to establish lower bound when input consists of N distinct

values a 1 through aN.

! Worst case dictated by tree height h.

! N! different orderings.

! (At least) one leaf corresponds to each ordering.

! Binary tree with N! leaves must have height:

h " log 2 ( N !) " log 2 ( N / e ) N = N log 2 N # N log 2 e. Stirling's formula