选择排序
public static void select_sort2(int[] arr){
for (int x = 0; x < arr.length - 1; x++){
int num = arr[x];//记录当前比较的数
int index = x;//记录当前角标
for (int y = x + 1; y < arr.length; y++){
if (num > arr[y]){
num = arr[y];
index = y;
}
}
//交换位置
if (index != x){
swap(arr,x,index);
}
}
}
冒泡排序
public static void bublleSort2(int[] arr){
for (int x = arr.length - 1; x > 0; x --){
for (int y = 0; y < x; y ++){
if (arr[y] > arr[y+1]){
swap(arr,y,y+1);
}
}
}
}
折半查找(只适用于已经排好序的数组)
public static int halfSearch(int[] arr, int key){
int min, max, mid;
min = 0;
max = arr.length - 1;
while (min <= max){
mid = (min + max) >> 1;//位运算,位右移一位相当于除于2
if (arr[mid] == key){
return mid;
}else if (arr[mid] > key){
max = mid - 1;
}else {
min = mid + 1;
}
}
return -1;
}
swap函数(交换数组中两个数的位置)
public static void swap(int[] arr, int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}