6.1冒泡排序
private static void bubbleSort(int[] arr) {
// 外循环: 控制比较的轮数
for (int i = 0; i < arr.length - 1; i++) {
// 内循环: 控制比较的次数
// -1避免索引越界, -i提高效率
for (int j = 0; j < arr.length - 1 - i; j++) {
// j = 0 1
// j = 1 2
// j = 2 3
// j = 3 4
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
6.2选择排序
public static void selectSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
6.3基本查找
数组遍历
6.4二分查找(折半查找)
public static int binarySearch(int num, int[] arr) {标签:基本,arr,temp,min,int,mid,算法,数组,length From: https://www.cnblogs.com/linzel/p/18087340
int min = 0;
int max = arr.length - 1;
while (min <= max) {
// 计算中间索引
int mid = (min + max) / 2;
// 比对
if (num > arr[mid]) {
min = mid + 1;
} else if (num < arr[mid]) {
max = mid - 1;
} else {
return mid;
}
}
return -1;
}