一、二分查
package com.tinner.algorithm
import sun.util.resources.cldr.eu.LocaleNames_eu
import javax.swing.tree.FixedHeightLayoutCache
/**
* @author Tinner
* @date 2019-11-17
* @Description 二分查找
*/
public class BinarySearch {
/**
* 使用递归完成二分查找
*
* @param arr 有序数组
* @param key 待查找关键字
* @param low
* @param hight
* @return 找到的位置
*/
public static int recursionBinarySearch(int[] arr, int key, int low, int hight) {
if (key < arr[low] || key > arr[hight] || low > hight) {
return -1
}
int middle = (low + hight) / 2
if (arr[middle] > key) {
return recursionBinarySearch(arr, key, low, middle - 1)
} else if (arr[middle] < key) {
return recursionBinarySearch(arr, key, middle + 1, hight)
} else {
return middle
}
}
/**
* 不使用递归完成二分查找
*
* @param arr 有序数组
* @param key 待查找关键字
* @return 找到的位置
*/
public static int commonBinarySearch(int[] arr, int key) {
int low = 0
int hight = arr.length - 1
int middle = 0
if (key < arr[low] || key > arr[hight] ||low > hight ) {
return -1
}
while (low <= hight) {
middle = (low + hight) / 2
if (arr[middle] > key) {
hight = middle - 1
} else if (arr[middle] < key) {
low = middle + 1
} else {
return middle
}
}
return -1
}
public static void main(String[] args) {
int[] arr = {1, 3, 5, 7, 9, 11}
int key = 9
int position = recursionBinarySearch(arr,key,0,arr.length - 1)
// int position = recursionBinarySearch(arr, key)
if (position == -1) {
System.out.println("查找的是" + key + ",序列中没有该数!")
} else {
System.out.println("查找的是" + key + ",找到位置为:" + position)
}
}
}
二、快速排序
package com.tinner.algorithm;
import java.util.Arrays;
public class QuickSort {
private static int count;
public static void main(String[] args) {
int[] nums = new int[]{
7, 1, 3, 5, 13, 9, 3, 6, 11
};
System.out.println("数组初始化为:" + Arrays.toString(nums));
sort(nums, 0, nums.length - 1);
System.out.println("经过快排之后:" + Arrays.toString(nums));
System.out.println("循环的次数为:" + count);
}
public static void sort(int[] array, int left, int right) {
if(left > right) {
return;
}
int base = array[left];
int i = left, j = right;
while(i != j) {
while(array[j] >= base && i < j) {
j--;
}
while(array[i] <= base && i < j) {
i++;
}
if(i < j) {
int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
array[left] = array[i];
array[i] = base;
count++;
sort(array, left, i - 1);
sort(array, i + 1, right);
}
}