快排,可以在len长度较小的时候,改用冒泡等简单的排序方式,因为len较小的时候,递归排序,需要栈操作,代价较大。
void fun(int[] a, int len) {
if(len <= 1) {
return;
}
boolean is_right = true;
int left = 0;
int right = len - 1;
int value = a[left];
while(left < right) {
if(is_right) {
if(a[right] <= value) {
a[left] = a[right];
is_right = !is_right;
left++;
} else {
right--;
}
}
else {
}
}
a[left] = value;
fun(a, left);
fun(a+left+1, len-left-1);
}
冒泡
4 5 3 2 1
1: 4 5 3 2
1 2 : 4 5 3
1 2 3 : 4 5
1 2 3 4 5
void fun(int a[], int len) {
for(int dst=0; dst<len-1; dst++) {
boolean hasChanged = false;
for(int src=len-1; src>dst; src--) {
if(a[src] < a[src-1]) {
swap(a[src], a[src-1]);
hasChanged = true;
}
}
if(!hasChanged) {
break;
}
}
}