一直在WEB上头忙活,SSH啦,EXT啦,Flex啦,乱七八糟的前端、框架。
近日由于一个机会警醒了作为基础的算法已经差劲到一定地步了~~~
先补了补排序算法,贴点自己的代码上来,都是已经运行过的。看了看时间,排10个数字不到1ms,进入排序方法10次。。。快。。。真快。。。
快排基本思想http://jackey25.iteye.com/blog/456646这位哥们已经说的非常清楚了。。。
public class QuickSort {
/**
* @param args
*/
public static void main(String[] args) {
QuickSort qs = new QuickSort();
int[] toSort = new int[] { 2, -8, 99, 0, -1, 37, 43, 88, 2, 82 };
long ss = System.currentTimeMillis();
toSort = qs.quickSort(toSort, 0, 0, toSort.length - 1);
println(System.currentTimeMillis() - ss);
printAll(toSort);
}
//int cnt;
/**
* @param toSort
* @param standard 作为比较标准数值的位置
* @param left 左端起点位置
* @param right 右端起点位置
*/
private int[] quickSort(int[] toSort,int standard, int left, int right) {
//print(cnt++ +"| standard: "+standard+",left:"+left+",right:"+right+": ");
//记住起始结束的位置
int l = left;
int r = right;
//没有相遇,则一直移动
while(l < r){
while(r > left && l < r){
//从右侧找到第一个小于标准数值的,结束右端本次查找
if(toSort[r] < toSort[standard]){
swap(toSort,r,standard);
break;
}
r--;
}
while(l < right && l < r){
//从左侧找到第一个大于标准数值的,结束左端本次查找
if(toSort[l] > toSort[standard]){
swap(toSort,l,standard);
break;
}
l++;
}
}
//没有小到1个元素1组之前继续分组
if(l > left){
quickSort(toSort,left,left,l-1);
}
if(r < right){
quickSort(toSort,r+1,r+1,right);
}
return toSort;
}
/**
* 交换数值
*/
private int[] swap(int[] toSort, int i, int j) {
int temp = toSort[i];
toSort[i] = toSort[j];
toSort[j] = temp;
return toSort;
}
private static void printAll(int[] toSort) {
for (int i = 0; i < toSort.length; i++) {
System.out.print(toSort[i] + ",");
}
System.out.println();
}
}