快速排序
static void _quick_sort(int array[], int start, int end){
int middle;
if(start >= end)
return;
middle = get_middle(array, start, end);
_quick_sort(array, start, middle -1);
_quick_sort(array, middle + 1, end);
}
private static int get_middle(int[] array, int start, int end) {
int tmp = array[start];
while (start < end) {
while (start < end && array[end] > tmp) {
end--;
}
array[start] = array[end];
while (start < end && array[start] <= tmp) {
start++;
}
array[end] = array[start];
}
array[start] = tmp;
output(array,"step"+ ++index +":");
return start;
}
static void quick_sort(int array[], int length){
index = 0;
if(null == array || 0 == length)
return;
_quick_sort(array, 0, length-1);
output(array,"");
}
改进冒泡
private static void bubble_sort(int[] array) {
index = 0;
int i_last_swap = -1;
int i_last_swap_tmp = 0;
for (int i = 0; i < array.length
&& (i_last_swap_tmp != i_last_swap)
&& (i_last_swap_tmp != array.length-1);
++i){
i_last_swap = i_last_swap_tmp;
System.out.println("["+i_last_swap+","+ (int)(array.length-1) +"]:");
for (int j = array.length - 1; j > i_last_swap; --j)
{
if (array[j] < array[j - 1])
{
int i_tmp = array[j];
array[j] = array[j - 1];
array[j - 1] = i_tmp;
i_last_swap_tmp = j;
output(array, "last_swap_loctaion:"+j+"\nsetp"+ ++index +":");
}
}
if (i_last_swap_tmp == i_last_swap)
{
System.out.println("已有序!");
}
}
return;
}
public static void ImproveBubble3(int [] array){
int low, up, _index, i;
low = 0;
up = array.length - 1;
_index = low;
while( up > low)
{
System.out.println("["+ low +","+ up +"]:");
for( i = low; i < up; i++)
{
if(array[i] > array[i + 1])
{
int i_tmp = array[i];
array[i] = array[i + 1];
array[i + 1] = i_tmp;
_index = i;
output(array, "last_swap_loctaion:"+ i +"\nsetp"+ ++index +":");
}
}
up = _index;
for(i = up; i > low; i--)
{
if(array[i] < array[i-1])
{
int i_tmp = array[i];
array[i] = array[i - 1];
array[i - 1] = i_tmp;
_index = i;
output(array, "last_swap_loctaion:"+ i +"\nsetp"+ ++index +":");
}
}
low = _index;
}
}