题目
随机排列链表,时间复杂度要求O(nlogn)。
思路 : 在归并排序的基础上,每次merge操作将辅助数组中的元素随机归并回原数组。
代码
import java.util.LinkedList;
import edu.princeton.cs.algs4.StdRandom;
public class ShufflingaLinkedList {
private static void merge(LinkedList<Comparable> temp, LinkedList<Comparable> a, int lo, int mid, int hi) {
//delete previous items
while(!temp.isEmpty())
temp.remove();
//cooy
for (int i = 0; i <= (hi-lo); i++) // hi-lo+1 is length of temp
temp.add(i, a.get(i+lo)); // add from [lo] to [hi]
//merge
for (int i = lo, j = 0; i <= hi; i++, j++) { // i is index of a, j is times of merge
int ind = StdRandom.uniform(hi-lo+1-j); // ind is between 0 and temp's length
a.remove(i);
a.add(i, temp.get(ind));
temp.remove(ind); // remove and temp's length - 1
}
}
public static void sort(LinkedList<Comparable> a) {
int len = a.size(), sz;
LinkedList temp = new LinkedList();
for (sz = 1; sz < len; sz *= 2) {
for (int lo = 0; lo < len - sz; lo += sz*2) {
merge(temp, a, lo, lo+sz-1, Math.min(lo+sz*2-1, len - 1));
}
}
}
public static void main(String []args) {
LinkedList test = new LinkedList();
for (int i = 0, k = 5; i < 5; i++, k--)
test.add(i, k);
sort(test);
for (int i = 0; i < 5; i++)
System.out.println(test.get(i));
}
}