Lec 03 - More Sorting
Stable Sort
A sorting algorithm is called stable if the relative order of elements with the same key value is preserved by the algorithm after sorting is performed.
Customized Sorting
As in Java, usually the Default Sorting if stable, what is sometimes we need a customized sorting? For example, the following Kattis problem is a good example.
To solve this problem, we need a customized sorting algo which will only sort based on the first two characters of the string. To implement the customized sorting, we can implement our own Comparator in Collections.sort() or Arrays.sort().
This customized sorting is implemented using a lambda expression on the functional interface Comparator in Java. In this case, (a, b) are the parameters, which matches the abstract method compare's parameter list. And the R.H.S is the computation, in this case, the comparison.
CS2030S Here! Great!
Fast I/O
Instead of using the standard I/O Scanner provided, we can use the fast I/O — BufferReader. Still use the Kattis problem above as the background, to use BufferReader in the problem, we can write the following code,
Notes
In
BufferReader, there is no token-based input, like.nextInt(), etc. There is only line-based input, so we need to parse the line by ourselves.A quick look at what
pw.close()does: Basically,pw.println()will print everything to the buffer first and once we callpw.close(), everything in the buffer will be printed.
Quick Sort
The whole idea of quick sort is pivot and three zones:
pivot: in quick sort, it is always chosen to be the first index (index 0) of the partition
three zone: the partition is always divided into 3 zones
the zone in which all the elements is smaller than the pivot
pivot
the zone in which all the elements are greater than the pivot
After each round, the pivot is put at the correct position. For visualization, go the goated website — VisualAlgo!
Random Quick Sort
It is a slight variation of quick sort, which picks the pivot randomly, and then swap the pivot with the first index element. Then the remaining are the same.
Counting Sort
I first learned counting sort in CS1010. The actual time complexity for counting sort is , where is the size of the frequency table.
One example is to use counting sort to solve the following leetcode
The code will look like
Last updated