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

49人阅读 评论(0)

快速排序与堆排序的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;
}
}

1
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：207次
• 积分：32
• 等级：
• 排名：千里之外
• 原创：3篇
• 转载：0篇
• 译文：0篇
• 评论：0条
文章分类
文章存档
阅读排行
评论排行