疯狂java


您现在的位置: 疯狂软件 >> 新闻资讯 >> 正文

选择排序之堆排序Java实现


 

   

  选择排序之堆排序Java实现

  public class Sort {

  /*

  * 堆排序

  */

  public static void heapSort(DataWrap[] data,int lastIndex){

  for (int i = (lastIndex-1)/2; i >=0; i--) {

  int index=i;

  while(index*2+1<=lastIndex){

  int biggerChild=index*2+1;

  if (biggerChild+1<=lastIndex) {

  if (data[biggerChild].compareTo(data[biggerChild+1])<0) {

  biggerChild++;

  }

  }

  if (data[index].compareTo(data[biggerChild])<0) {

  swap(data, index, biggerChild);

  index=biggerChild;

  }else {

  break;

  }

  }

  }

  }

  /*

  * 交换数组元素

  */

  public static void swap(DataWrap[] data,int i,int j){

  DataWrap temp=data[i];

  data[i]=data[j];

  data[j]=temp;

  }

  }

  /*

  *定义一个数据包装类

  */

  class DataWrap implements Comparable{

  int data;

  String flag;

  public DataWrap() {

  // TODO Auto-generated constructor stub

  }

  public DataWrap(int data,String flag) {

  this.data=data;

  this.flag=flag;

  }

  @Override

  public String toString(){

  return data+flag;

  }

  @Override

  public int compareTo(DataWrap o) {

  // TODO Auto-generated method stub

  return this.data>o.data?1:(this.data==o.data?0:-1);

  }

  }