- 选择排序
//选择排序 从小到大
private static void xuanZe() {
int [] array = {8,5,4,3,7,2,9,6,1};
for (int i = 0; i < array.length; i++) {
for (int j = i+1; j < array.length; j++) {
if (array[i]>array[j]){//拿第一个数与后面的数挨个进行比较,遇到小于第一个的数进行相互赋值,第一次循环结束拿到数组中小的值
int num = array[i];
array[i] = array[j];
array[j] = num;
}
}
System.out.print(array[i]);//第一轮循环结束拿到最小的值(或者最大的值)
}
System.out.println("");
for (int k = 0; k <array.length ; k++) {
System.out.println(array[k]);
}
}
- 冒泡排序
//冒泡排序 从小到大
private static void maoPao() {
int [] array = {8,5,4,3,7,2,9,6,1};
for (int i = 0; i < array.length-1; i++) {
for (int j = 0; j < array.length-i-1; j++) {
if (array[j]>array[j+1]){//比较交换相邻元素 两两对比,大数后移
int num = array[j];
array[j] = array[j+1];
array[j+1] = num;
}
}
}
for (int k = 0; k <array.length ; k++) {
System.out.print(array[k]);
}
}
- 二分法查找
- 非递归
//二分法查找 非递归
public static int binarySearch(int[] arr,int value){
//low低数 high高数
int low = 0,high = arr.length - 1;
int mid = 0;//中间数
while(low <= high){
mid = (low + high)/2;//求中间数
if(arr[mid] == value){//当中间数value值正确时。拿到所在数组下标
return mid;//返回下标
}
if(arr[mid] < value){//如果中间数小于value值。则可得到,value值在上半部分
low = mid + 1;//将最小数改为中间值+1。下面同理
}else if(arr[mid] > value){
high = mid - 1;
}
}
return -1;
}
- 递归
public static int erFenFa(int[] arr, int value, int footer, int header){
if (header < footer){
return -1;
}
int middle = (header + footer)/2;
if (arr[middle] == value){
return middle;
}
if (arr[middle]<value){
footer = middle + 1;
return erFenFa(arr,value,footer,header);
}else{
header = header - 1;
return erFenFa(arr,value,footer,header);
}
}
- 字符串查重
//字符串查重
private static void charDemo(){
String str = "helloword";
char[] arr = str.toCharArray();
//查询每个字母出现的次数,并根据字母进行排序,故采用TreeMap
Map<String, Integer> treeMap = new TreeMap<>();
for (int i = 0; i < arr.length; i++) {
if (treeMap.containsKey(arr[i]+"")){
Integer num = treeMap.get(arr[i] + "");
num++;
treeMap.put(arr[i]+"",num);
}else{
treeMap.put(arr[i]+"",1);
}
}
treeMap.forEach((k,v)->{
System.out.println(k+"="+v);
});
}
Q.E.D.