package xie.struct;
import java.util.ArrayList;
public class Sortextends Comparable> {
public static final int QuickSort = 1;
public static final int SelectMin = 4;
public static final int MaoPao = 3;
public static final int HeapSort = 2;
private ArrayList data;//数据存储
public Sort() {
}
public void runSort(int mode) {
switch (mode) {
case 1:
System.out.println("快速排序输出:");
this.QuickSort(data, 0, data.size() - 1);
break;
case 2:
System.out.println("堆排序输出:");
this.heapSort();
break;
case 3:
System.out.println("冒泡排序输出:");
this.MaoPao();
break;
case 4:
break;
default:
break;
}
}
public void setData(ArrayList a) {
this.data = a;
}
public void addData(T data) {
this.data.add(data);
}
public String toString() {
for (int i = 0; i )
System.out.print(data.get(i) + "/");
return null;
}
public void MaoPao()
{
int i,j;
int n=this.data.size();
for(i=0;i)
for(j=1;j){
if(this.data.get(j-1).compareTo(this.data.get(j))>0)
{
T swap=this.data.get(j);
this.data.set(j,this.data.get(j-1));
this.data.set(j-1,swap);
}
}
}
/*
* 快速排序代码
*/
private void QuickSort(ArrayList a, int left, int right) {
if (left < right) {
int low = left;
int high = right;
T key = a.get(low);
while (low < high) {
while (low = 0)
high--;
a.set(low, a.get(high));
while (low )
low++;
a.set(high, a.get(low));
}
a.set(low, key);
QuickSort(a, left, low - 1);
QuickSort(a, low + 1, right);
}
}
/*
*
* 堆排序函数代码
*/
private void buildHeap() {
int len = this.data.size();
int i;
for (i = len / 2 - 1; i >= 0; i--)
this.adjustHeap(i);
}
private void adjustHeap(int index) {
int len = this.data.size();
int left = index * 2 + 1;
int right = index * 2 + 2;
int smaller = left;
T swap;
if (left > len - 1)
return;
if (right < len
&& this.data.get(left).compareTo(this.data.get(right)) > 0) {
smaller = right;
}
if (smaller < len
&& this.data.get(index).compareTo(this.data.get(smaller)) > 0) {
swap = this.data.get(smaller);
this.data.set(smaller, this.data.get(index));
this.data.set(index, swap);
this.adjustHeap(smaller);
}
}
private void heapSort() {
this.buildHeap();
int len = this.data.size();
while (len > 0) {
System.out.print(this.data.get(0)+"/");
this.data.set(0, this.data.get(len - 1));
this.data.remove(len - 1);
len--;
this.adjustHeap(0);
}
}
/*
*
* 测试代码
*/
public static void main(String args[]) {
ArrayList array = new ArrayList();
array.add("A");
array.add("D");
array.add("G");
array.add("H");
array.add("S");
array.add("J");
array.add("B");
Sort sort = new Sort();
sort.setData(array);
sort.runSort(Sort.QuickSort);
sort.toString();
sort.setData(array);
sort.runSort(Sort.MaoPao);
sort.toString();
sort.setData(array);
sort.runSort(Sort.HeapSort);
}
}