陣列排序的測試

chance2000發表於2006-03-28

直接插入排序、折半插入排序、2-路插入排序

程式碼如下...

[@more@]
public class testSort {
public static void main(String[] args) {
String[] x = {"bb" ,"aa" ,"pp" ,"xx" ,"yy"} ;
StringPrint(x ,"Before Sort:") ;
InsertSort(x) ;
StringPrint(x ,"After Sort:") ;
String[] y = {"bb" ,"aa" ,"pp" ,"xx" ,"yy"} ;
StringPrint(y ,"Before Sort:") ;
BInsertSort(y) ;
StringPrint(y ,"After Sort:") ;
}
public static void StringPrint(String[] x ,String header) {
System.out.println(header) ;
StringBuffer sb = new StringBuffer() ;
for(int i = 0 ;i < x.length ;i ++)
sb.append(x[i]).append(" ") ;
System.out.println(sb.toString()) ;
}
/**
* 直接插入排序
*/
public static void InsertSort(String[] x) {
String t = new String() ;
int i = 0 ,j = 0 ;
for(i = 1 ;i < x.length ;++ i) {
if(!Compare(x[i] ,x[i - 1])) {
t = x[i] ;
for(j = i - 1 ;j >= 0 && Compare(x[j] ,t) ;-- j)
x[j + 1] = x[j] ;
x[j + 1] = t ;
}
}
}
/**
* 折半插入排序
*/
public static void BInsertSort(String[] x) {
String t = new String() ;
int i = 0 ,j = 0 ,low = 0 ,high = 0 ,m = 0 ;
for(i = 1 ;i < x.length ;++ i) {
t = x[i] ;
low = 0 ;
high = i - 1 ;
while(low <= high) {
m = (low + high) / 2 ;
if(Compare(x[m] ,t)) high = m - 1 ;
else low = m + 1 ;
}
for(j = i - 1 ;j >= high + 1 ;-- j)
x[j + 1] = x[j] ;
x[high + 1] = t ;
}
}
/**
* 2-路插入排序
*/
public static void TwoInsertSort(String[] x) {
String[] v = new String[x.length] ;
int first = 0 ,final = 0 ;
v[0] = x[0] ;
}
public static boolean Compare(String a ,String b) {
if(a.compareTo(b) > 0) return true ;
else return false ;
}
}

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/802415/viewspace-823653/,如需轉載,請註明出處,否則將追究法律責任。

相關文章