# 快速排序与堆排序的Java实现（泛型）

## 快速排序与堆排序的Java实现（泛型）

### 快排

package quicksort;

import java.util.List;
import java.util.ListIterator;

public class QuickSort {

@SuppressWarnings("unchecked")
public static <E extends Comparable<? super E>> void sort(List<E> list) {
Object[] objs = list.toArray();
partition(objs, 0, objs.length-1);
ListIterator<E> iterator = list.listIterator();
for(int i=0; i<objs.length; ++i) {
iterator.next();
iterator.set((E)objs[i]);
}
}

private static void partition(Object[] objs, int left, int right) {
if(left >= right) return;
int i = left;
int j = right;
@SuppressWarnings("unchecked")
Comparable<Object> temp = (Comparable<Object>)objs[i];
while( i < j ) {
while(temp.compareTo(objs[j]) < 0 && i<j) --j;
if(i == j) break;
objs[i] = objs[j];
++i;
while(temp.compareTo(objs[i]) > 0 && i<j) ++i;
if(i == j) break;
objs[j] = objs[i];
--j;
}
objs[i] = temp;
partition(objs, left, i-1);
partition(objs, i+1, right);
}
}

### 堆排序

package heapsort;

import java.util.ArrayList;
import java.util.List;

public class HeapSort {

public static <E extends Comparable<? super E>> void sort(List<E> list) {
if(list == null || list.size() == 0) return;
Object[] a = list.toArray();
buildHeap(a);
int index = a.length-1;
while(index > 0) {
swap(a, 0, index);
--index;
reBuildHeap(a, 0, index);
}
print(a);
}

@SuppressWarnings("unchecked")
private static void reBuildHeap(Object[] a, int firstIndex, int lastIndex) {
int i = firstIndex;
int j = i*2 + 1;
while(j<=lastIndex) {
Comparable<Object> compAj = (Comparable<Object>)a[j];
if(j<lastIndex) {
if(compAj.compareTo(a[j+1]) < 0) {
++j;
compAj = (Comparable<Object>)a[j];
}
}
if(compAj.compareTo(a[i]) > 0) swap(a, i, j);
i = j;
j = i*2 + 1;
}
}

private static void buildHeap(Object[] a) {
int index = a.length-1;
index = (index-1)/2;
while( index >= 0) {
reBuildHeap(a, index, a.length-1);
--index;
}
}

private static void print(Object[] a) {
for(Object i:a) {
System.out.print(i + " ");
}
System.out.println();
}

private static void swap(Object[] a , int i, int j) {
Object temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}


• 本文已收录于以下专栏：

举报原因： 您举报文章：快速排序与堆排序的Java实现（泛型） 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)