疯狂java


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

交换排序之快速排序Java实现


 

交换排序之快速排序Java实现
 
交换排序之快速选择排序Java实现
public class Sort {
<span style="white-space:pre"> </span>/*
* 快速排序
*/
public static void quickSort(DataWrap[] data,int start,int end){
if (start<end) {
DataWrap base=data[start];
int i=start;
int j=end+1;
while(true){
while(i<end && data[++i].compareTo(base)<=0);
while(j>start && data[--j].compareTo(base)>=0);
if (i<j) {
swap(data, i, j);
}else{
break;
}
}
swap(data, start, j);
quickSort(data, start, j-1);
quickSort(data, j+1, end);
}
}
public static void main(String[] args) {
DataWrap[] dataWraps={
new DataWrap(231,""),
new DataWrap(31,""),
new DataWrap(2,""),
new DataWrap(2338,"*"),
new DataWrap(2122,""),
new DataWrap(22,""),
new DataWrap(55,""),
new DataWrap(134,""),
new DataWrap(24000,"")
};
System.out.println("排序之前:"+Arrays.toString(dataWraps));
quickSort(dataWraps, 0, dataWraps.length-1);
System.out.println("排序之后:"+Arrays.toString(dataWraps));
 
/* * 交换数组元素 */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<DataWrap>{int data;String flag;public DataWrap() {// TODO Auto-generated constructor stub}public DataWrap(int data,String flag) {this.data=data;this.flag=flag;}@Overridepublic String toString(){return data+flag;}@Overridepublic int compareTo(DataWrap o) {// TODO Auto-generated method stubreturn this.data>o.data?1:(this.data==o.data?0:-1);}}