排序
package com.test;
public class Math {
public static void main(String[] args) {
int[] arr = { 1, 5, 2, 6, 9, 3 };
int[] arr2 = { 1, 3, 6, 8, 9 };
//sys(arr);
System.out.println("-------------");
// selectSort(arr);
// sort(arr);
int index = search_2(arr2, 9);
System.out.println("index:" + index);
// sys(arr);
}
// 打印
public static void sys(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
}
System.out.println();
}
// 快速排序
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;
}
}
}
}
// 冒泡排序
public static void sort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
/**
* 相邻两个元素比较,每次外层循环结束后,可以确定最大值,
* 所以减i,去掉最后一个元素,减1是避免数组越界
*/
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// 折半查找1(折半查找前提是:数组元素必须是有序的)
public static int search_1(int[] arr, int key) {
int min = 0;
int max = arr.length - 1;
int mid = (min + max) / 2;
while (arr[mid] != key) {
if (key > arr[mid])
min = mid + 1;
else
max = mid - 1;
if (min > max)
return -1;
mid = (min + max) / 2;
}
return mid;
}
// 折半查找2
public static int search_2(int[] arr, int key) {
int min = 0;
int max = arr.length - 1;
int mid = (max + min) >> 1;
while (min <= max) {
if (key > arr[mid])
min = mid + 1;
else if (key < arr[mid])
max = mid - 1;
else
return mid;
mid = (max + min) >> 1;
}
return -1;
}
}