In many cases, sorting aims to classify data, which has many duplicate values.
- Population statistics by age
- Delete duplicate emails in the email list
- Sort job seekers by University
If you sort repeated data using a normal fast sort, the complexity of N ^ 2 will be caused, but there is no such problem between the merge sort and the three-way fast sort.
The comparison between 1/2nlgn and nlgn
Three routes
Objective: To divide data into three intervals (3-way partitioning)
- The elements in the LT and GT ranges are equal to the comparison element V.
- Lt. The element on the left is smaller than v.
- The element on the Right of GT is larger than v.
Performance
The complexity of the three-way fast sorting is smaller than that of the normal fast sorting, mainly depending on the number of duplicate data in the data. The more duplicate data, the more complex the three-way fast sorting is.
JAVA Implementation
private static void sort(Comparable[] a, int lo, int hi){ if (hi <= lo) return; int lt = lo, gt = hi; Comparable v = a[lo]; int i = lo; while (i <= gt) { int cmp = a[i].compareTo(v); if (cmp < 0) exch(a, lt++, i++); else if (cmp > 0) exch(a,i,gt--); else i++; } sort(a, lo, lt - 1); sort(a, gt + 1, hi); }
- A [I] <v: Switching A [lt] And a [I], LT and I increase by 1, respectively.
- A [I]> V: Switching A [gt] And a [I], GT decreases by 1
- A [I] = V: I increments by 1
- Note: GT does not scan independently. The value of GT is decreased only after a [I] is exchanged with a [gt ].
Algorithm class algorithm part I week 3 duplicate element sorting-three-way fast duplicate keys