1. Java中冒泡排序
class="java">
public class BubbleSortTest{
public static void bubbleSort(int[] array){
for(int i = 0; i < array.length - 1; i++){
for(int j = 0; j < array.length - i - 1; j++){
if(array[j] > array[j + 1]){
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
System.out.print("第" + (i + 1) + "趟排序:");
for(int k = 0; k < array.length; k++){
System.out.print(array[k] + " ");
}
System.out.println();
}
}
public static void main(String[] args){
int[] array = {4, 7, 8, 9, 3, 2};
bubbleSort(array);
}
}
运行结果:
第1趟排序:4 7 8 3 2 9
第2趟排序:4 7 3 2 8 9
第3趟排序:4 3 2 7 8 9
第4趟排序:3 2 4 7 8 9
第5趟排序:2 3 4 7 8 9
2. Java中二分查找
public class ArraySearchTest{
public static int search(int[] array, int value){
for(int i = 0; i < array.length; i++){
if(value == array[i]){
return i;
}
}
return -1;
}
public static int binarySearch(int[] array, int value){
int low = 0;
int high = array.length - 1;
int middle;
while(low <= high){
middle = (low + high) / 2;
for(int i = 0; i < array.length; i++){
System.out.print(array[i]);
if(i == middle){
System.out.print("#");
}
System.out.print(" ");
}
System.out.println();
if(array[middle] == value){
return middle;
}
if(value < array[middle]){
high = middle - 1;
}
if(value > array[middle]){
low = middle + 1;
}
}
return -1;
}
public static void main(String[] args){
int[] a = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9};
int value = 8;
int index = search(a, value);
System.out.println(index);
System.out.println("-----------------");
int[] b = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9};
int index2 = binarySearch(b , 4);
System.out.println(index2);
}
}
运行结果:
7
-----------------
1 2 3 4 5# 6 7 8 9
1 2# 3 4 5 6 7 8 9
1 2 3# 4 5 6 7 8 9
1 2 3 4# 5 6 7 8 9
3