操作1,获取数组的最大值和最小值:
获取最大值:
public static int getMax() {
int[] arr = { 1, 2, 3, 4, 5, 6, 7 };
int max = arr[0];
for (int i = 0; i < arr.length; i++) {
if (max < arr[i]) {
max = arr[i];
}
}
return max;
}
获取最小值:
public static int getMin() {
int[] arr = { 8, 2, 3, 4, 5, 6, 7 };
int min = arr[0];
for (int i = 0; i < arr.length; i++) {
if (min > arr[i]) {
min = arr[i];
}
}
return min;
}
操作2:数组排序:
选择排序:
原理示意图:
public static void printArr(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + "\t");
}
System.out.println();
}
int[] arr = { 1, 3, 5, 7, 2, 4, 6 };
for (int i = 0; i < arr.length - 1; i++) {// 因为最后一个元素不用在比较了
for (int j = i + 1; j < arr.length; j++) {
int temp;
if (arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
冒泡排序:
原理示意图:
public static void sort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
int temp;
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
printArr(arr);
}
操作3:查找是否存在某个元素:
普通查找方式:
public static int search(int[] arr, int target) {
if (arr.length > 0) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
return i;
}
}
}
return -1;
}
折半查找法:
原理示意图:
public static int halfSearch(int target) {
int[] arr = { 1, 2, 3, 4, 5, 6 };
int min, max, mid;
min = 0;
max = arr.length - 1;
mid = (min + max) / 2;
while (arr[mid] != target) {
if (arr[mid] > target) {
max = mid - 1;
} else if (arr[mid] < target) {
min = mid + 1;
}
if (min > max) {// 如果数组没有这个元素
return -1;
}
mid = (min + max) / 2;
}
return mid;
}
另一种折半查找方式:
public static int halfSearch2(int target) {
int[] arr = { 1, 2, 3, 4, 5, 6, 7 };
int min, max, mid;
min = 0;
max = arr.length - 1;
while (min <= max) {
mid = (min + max) / 2;
if (target > arr[mid]) {
min = mid + 1;
System.out.println(min);
} else if (target < arr[mid]) {
max = mid - 1;
} else {
return mid;
}
}
return -1;
}