快速排序
public int partition(int[] a, int start, int end) throws IllegalArgumentException {
if (a == null || a.length == 0 || start < 0 || end >= a.length) {
throw new IllegalArgumentException("");
}
int index = randomRange(start, end);
swap(a, index, end);
int small = start - 1;
for (index = start; index < end; index++) {
if (a[index] < a[end]) {
small++;
if (small != index) {
swap(a, small, index);
}
}
}
small++;
swap(a, small, end);
return small;
}
private int randomRange(int start, int end) {
int ret = 0;
Random random = new Random();
ret = start + random.nextInt(end - start);
// ret = (start + end) /2;
System.out.print(start + "," + end + ",ret=" + ret + " ");
return ret;
}
private void swap(int[] a, int first, int second) {
if (a == null || a.length == 0 || first < 0 || second < 0) {
throw new IllegalArgumentException("invalid data");
}
int temp = a[first];
a[first] = a[second];
a[second] = temp;
}
public void quickSort(int[] a, int start, int end) {
if (a == null || a.length == 0) {
return;
}
if (start == end) {
return;
}
int index = partition(a, 0, a.length - 1);
if (index > start) {
quickSort(a, start, index - 1);
}
if (index < end) {
quickSort(a, index + 1, end);
}
}
//找到第k大的數
public int findKTh(int[] a, int k) {
if (a == null || a.length == 0 || k <= 0) {
throw new IllegalArgumentException("Invalid data");
}
int index = partition(a, 0, a.length - 1);
int n = a.length;
if (index == (n - k)) {
return a[index];
}
while (index != (n - k)) {
if (index > (n - k)) {
index = partition(a, 0, index - 1);
} else if (index < (n - k)) {
index = partition(a, index + 1, a.length - 1);
}
}
return a[index];
}
測試case:(僅包含了功能測試,還需要邊界測試)
public class Exam2_4_2Test { Exam2_4_2 exam2_4_2; @Before public void init() { exam2_4_2 = new Exam2_4_2(); } @Test public void quickSort() { int[] a = {3, 1, 5, 2, 8, 6, 9}; exam2_4_2.quickSort(a, 0, a.length - 1); printArray(a); } private void printArray(int[] a) { if (a == null || a.length == 0) throw new IllegalArgumentException("invalid data"); for (int i = 0; i < a.length; i++) { System.out.println("a[" + i + "]=" + a[i]); } } @Test public void findKTh() { int[] a = {3, 1, 5, 2, 8, 6, 9}; int third = exam2_4_2.findKTh(a, 3); //第三大對應的應該是6。 System.out.println("third=" + third); } }
基於劍指offer,以及網絡文章:
https://www.cnblogs.com/wangkundentisy/p/8810077.html
在此表示感謝。