最近想学点分类算法,在写决策树算法的时候对于连续变量要先进行排序,于是就自己先写了一个快排的算法。思路照着百度百科上的C语言版本学的,但是由于java中没有指令的存在,所以必须要在一些方面做些变通,修改了异常处理模块,并增加了一个合并两个字符串的函数。
public class QuickSort{
/**
* 快速排序
* @author Multiangle from Southeast University
*/
public static void main(String[] args){
int[] a={5,1,3,4,6,13,4,12,9,12,7,5,7,1,11} ;
int[] rs=Sort(a,0,a.length-1) ;
for(int i=0;i<rs.length;i++){
System.out.print(rs[i]+" ");
}
}
public static int[] Sort(int[] input,int low,int high){
System.out.println("进行 "+low+" 到 "+high+" 的排序") ;
if(low>=high) return null ; //这一段处理元素调动
int first=low ;
int last=high ;
int key=input[low] ;
while(first<last){
while((first<last)&&(input[last]>=key)) --last ;
input[first]=input[last] ;
while((first<last)&&(input[first]<=key)) ++first ;
input[last]=input[first] ;
}
input[first]=key ;
int[] res1,res2 ; //这一段处理异常情况
if (first-1>low) {
res1=Sort(input,low,first-1) ;
}else if(first-1==low) {
int[] temp={input[low]} ;
res1=temp ;
}else{
res1=null ;
}
if(high>first+1){
res2=Sort(input,first+1,high) ;
}else if(high==first+1){
int[] temp={input[high]} ;
res2=temp ;
}else{
res2=null ;
}
int[] finalres ;
finalres=Combine(res1,res2,key) ;
return finalres ;
}
private static int[] Combine(int[] res1,int[] res2,int key){
int len1,len2 ;
if(res1==null) len1=0 ;
else len1=res1.length ;
if(res2==null) len2=0 ;
else len2=res2.length ;
int[] res=new int[len1+len2+1] ;
int index=0 ;
for(int i=0;i<len1;i++) res[index++]=res1[i] ;
res[index++]=key ;
for(int i=0;i<len2;i++) res[index++]=res2[i] ;
return res ;
}
}