1.冒泡排序
public class BubbleSort {
public int sort1(int[] array){
//计数器,计算比较了多少次
int count = 0;
int k,flag = array.length,temp;
//当运行完一次之后,如果flag没变,则排序完成
while(flag > 0){
//k为右边界
k = flag;
//flag 为左边界
flag = 0;
for(int i = 1; i < k; i++){
count++;
if(array[i] < array[i - 1]){
temp = array[i];
array[i] = array[i - 1];
array[i - 1] = temp;
flag = i;
}
}
}
return count;
}
public int sort2(int[] array){
int count = 0,temp;
for(int i = 0; i < array.length; i ++){
for(int j = i + 1; j < array.length; j ++){
count ++;
if(array[i] > array[j]){
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
return count;
}
public static void main(String[] args) {
BubbleSort bs = new BubbleSort();
int[] array = new int[]{1,4,2,3,5};
System.out.println(bs.sort1(array));
printArray(array);
array = new int[]{1,4,2,3,5};
System.out.println(bs.sort2(array));
printArray(array);
}
public static void printArray(int[] array){
for(int item : array){
System.out.print(item + " ");
}
System.out.println();
}
}
2.
快速排序
思路:基于分治的思想,是冒泡排序的改进型。
1.分别从数组的两端扫描数组,设两个指示标志(lo指向起始位置,hi指向末尾),首先从后半部分开始,如果发现有元素比该基准点的值小,就交换lo和hi位置的值,
2.然后从前半部分开始扫秒,发现有元素大于基准点的值,就交换lo和hi位置的值,
3.如此往复循环,直到lo>=hi,然后把基准点的值放到hi这个位置。一次排序就完成了。
4.以后采用递归的方式分别对前半部分和后半部分排序,当前半部分和后半部分均有序时该数组就自然有序了。
public class QuicklySort {
private int count = 0;
public int position(int[] array, int low, int hight){
while(low < hight){
while(array[hight] >= array[low] && low < hight){
count ++;
hight --;
}
int key = array[low];
array[low] = array[hight];
array[hight] = key;
while (array[low] <= array[hight] && low < hight){
count ++;
low ++;
}
key = array[hight];
array[hight] = array[low];
array[low] = key;
}
return low;
}
public void sort(int[] array, int low, int high){
if(low >= high){
return;
}
int index = position(array,low,high);
sort(array,low,index - 1);
sort(array,index + 1, high);
}
public static void main(String[] args) {
int[] array = new int[]{1,5,4,6,2,3,8,7,8,9};
QuicklySort qs = new QuicklySort();
qs.sort(array,0,array.length - 1);
System.out.println(qs.count);
BubbleSort.printArray(array);
BubbleSort bs = new BubbleSort();
array = new int[]{1,5,4,6,2,3,8,7,8,9};
System.out.println(bs.sort2(array));
BubbleSort.printArray(array);
}
}
3.
问题测试
1. | 对于快速排序时,如果index = 0,或者 index = length - 1;会不会报数组越界异常呢? |
经测试不会, 当index = 0,在sort方法的判断low >= high为true,直接返回了 index = length - 1时亦然。 |