Skip to content

Commit 287a85f

Browse files
Start to review the basic about sorting from Princeton course. Need to cover mergesort, quicksort, heap.
1 parent 33475d8 commit 287a85f

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# Sorting Introduction
2+
3+
## Interface
4+
- Generic sort relies on Comparable Interface.
5+
- Each type should implement CompareTo. ( Callback mechanism)
6+
- The CompareTo should follow total order and output negative, 0,plus if it's smaller, equal and larger than the other.
7+
- Each sort algorithm should target Comparable Interface.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
public class Selection
2+
{
3+
public static void sort(Comparable[] a)
4+
{
5+
int N=a.length;
6+
for(int i=0;i<N;i++)
7+
{
8+
int min=i;
9+
for(int j=i+1;j<N;j++)
10+
{
11+
if(less(a[j],a[min]))
12+
min=j;
13+
}
14+
exch(a,i,min);
15+
}
16+
}
17+
18+
private static boolean less(Comparable v, Comparable w)
19+
{ return v.compareTo(w) < 0; }
20+
21+
private static void exch(Comparable[] a, int i, int j)
22+
{
23+
Comparable swap = a[i];
24+
a[i] = a[j];
25+
a[j] = swap;
26+
}
27+
28+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# Selection Sort
2+
3+
## Mechanism
4+
- Find the index of min of the remaining entry
5+
- Swap i and that index.
6+
7+
## Properties of selection sort
8+
- O(N^2), even if the input is sorted
9+
- O(N) exchange. Minimum dave movement.
10+
11+
## Complexity
12+
- N^2/2 compare
13+
- N exchange

0 commit comments

Comments
 (0)