https://oj.leetcode.com/tag/sort/
#1 归并排序,核心思想是分治。无序拆分 有序合并
适合链表。不适合数组,无法inplace。
https://oj.leetcode.com/problems/sort-list/
merge:
A3:https://oj.leetcode.com/problems/merge-sorted-array/
http://lintcode.com/en/problem/merge-sorted-array/
A4:https://oj.leetcode.com/problems/merge-two-sorted-lists/ (基)
A4-B:https://oj.leetcode.com/problems/merge-k-sorted-lists/
#2 快速排序,最佳适用于数组,核心思想是分治。有序拆分 直接合并
适合数组,可以inplace。链表也可以
partition:对于数组就是双指针交换 (基重)
private static int partition(Integer A[], int left, int right) {
// 最左为pivot
int pivot = left; // left切不可挪动 当最左为最小值时 有机会返回最左点
while (left < right) {
//必须先挪右边 当最左为最小值时 有机会返回最左点(这是由pivot在最左决定的)
if (A[right] > A[pivot]) --right;
else if (A[left] <= A[pivot]) ++left; //等号给这里是为了暂时不挪动pivot
else swap(A, left, right); // 如果写成 swap(A, left--, right++) 会导致right<left 或者right==left 看另外一种写法
}//退出时 right一定指向小于pivot的元素或者指向pivot
swap(A, pivot, end);//此时左右相等 可以写成right(由while(left<right)导致这里左右相等)
return end; //可以写成right
}
private static int partition(Integer A[], int left, int right) {
// 最左为pivot
int pivot = left; // left切不可挪动 当最左为最小值时 有机会返回最左点
while (left <= right) {
//必须先挪右边 当最左为最小值时 有机会返回最左点(这是由pivot在最左决定的)
if (A[right] > A[pivot]) --right;
else if (A[left] <= A[pivot]) ++left; //等号给这里是为了暂时不挪动pivot
else swap(A, left++, right--); // 可以如果写成 swap(A, left, right)
}
swap(A, pivot, end);//必须写成end 原因是结束while循环的时候right < left 因为先右后左 所以用end
return end; //必须写成end
}
如果使用最右为pivot,必须先挪动最左点。
http://www.lintcode.com/en/problem/partition-array/A1:https://oj.leetcode.com/problems/sort-colors/ (难)三指针
A2:https://oj.leetcode.com/problems/partition-list/
A6-1:https://oj.leetcode.com/problems/two-sum/
A6-2:https://oj.leetcode.com/problems/3sum/
A6-3:https://oj.leetcode.com/problems/3sum-closest/
A6-4:https://oj.leetcode.com/problems/4sum/
无序数组中找第K大的数 (重)
#3 堆排序,可由数组实现。优先队列由堆实现。
基本操作:
#1 删除头元素:尾节点替换头结点,产生logn的sink操作。
#2 插入元素:新节点加入尾部之后,产生logn的swim操作。
排序:
#1 构造堆nlogn:从最后一个非叶子节点开始到头结点,sink操作。
#2 排序nlogn:交换头尾节点,减少堆元素数量,头结点sink。循环到堆里没有元素。
https://oj.leetcode.com/tag/heap/
A4-B:https://oj.leetcode.com/problems/merge-k-sorted-lists/
#4 插入排序 O(N^2)
E8:https://oj.leetcode.com/problems/insertion-sort-list/
#5 Radix排序 O(KN)
https://oj.leetcode.com/problems/maximum-gap/
#6 其他
I3: https://oj.leetcode.com/problems/merge-intervals/
I4: https://oj.leetcode.com/problems/insert-interval/
https://leetcode.com/problems/missing-ranges/ 每个数跟lower,upper比较,改变lower或者upper,必要时生成结果
https://oj.leetcode.com/problems/largest-number/