githubEdit

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 expressionarrow-up-right on the functional interface Comparatorarrow-up-right 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.

circle-check

Fast I/O

Instead of using the standard I/O Scannerarrow-up-right provided, we can use the fast I/O — BufferReaderarrow-up-right. Still use the Kattis problem above as the background, to use BufferReader in the problem, we can write the following code,

circle-check

Notes

Quick Sort

The whole idea of quick sort is pivot and three zones:

  1. pivot: in quick sort, it is always chosen to be the first index (index 0) of the partition

  2. three zone: the partition is always divided into 3 zones

    1. the zone in which all the elements is smaller than the pivot

    2. pivot

    3. 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 — VisualAlgoarrow-up-right!

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 CS1010arrow-up-right. The actual time complexity for counting sort is O(k+n)O(k+n), where kk 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