排序:sort
**冒泡:每次分别拿两个数进行比较,把大的放到后面,全部比较一次结束后,保证最大的数放在最末尾。**
package com.lx;
import java.util.Arrays;
public class Test_maopao {
public static void main(String[] args) {
int [] arr = {2,36,7,22,54,12,8};
sortBubble(arr);
System.out.println(Arrays.toString(arr));
}
//定义方法(冒泡排序)
public static void sortBubble(int[] arr){
//int temp; 优化后:提升变量
for(int i=0;i<arr.length;i++){//i代表的是趟数(全部比较一次,总共需要多少次)
for(int j=0;j<arr.length-1-i;j++){
if(arr[j]>arr[j+1]){
//把两个数进行交换
/*
* 优化:不用频繁的定义变量 (提升变量作用域)
* 报错信息:ArrayIndexOutOfBoundsException 越界异常
*/
int temp = arr[j+1];//优化后 temp = arr[j+1];
arr[j+1] = arr[j];
arr[j] = temp;
}
}
}
}
}
//定义方法(交换两个数的方法)
public static void swap(int a,int b){
/*int temp = a;
a = b;
b = temp;*/
//要求:不需要使用第三个变量
/*a = a+b;
b = a-b; /b=(a+b)-b=a
a = a-b;*/
a = a^b;
b = a^b;
a = a^b;
System.out.println("swap方法中:a="+a+";b="+b);
}
选择:拿第一个数,分别和接下来的剩下的数进行比较,保留其中最小的数的索引,然后把它和当前正在
对比的数进行交换,保证把最小的数可以放在最开始
//定义方法(选择排序)
public static void sortSelect(int[] arr){
for(int i=0;i<arr.length;i++){
int minIndex = i;
for(int j=i;j<arr.length;j++){
//找到最小的数
if(arr[j]<arr[minIndex]){
//最小数的索引保存
minIndex = j;
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
二分查找法:
//二分查找法() 大前提,数组必须是有序的
public static int binarySearch(int[] arr,int value){
//定义两个指针,low和high
int low = 0;
int high = arr.length-1;
while(low<=high){
int mid = (low+high)/2;
if(value<arr[mid]){
//在前半段查找,
high = mid-1;
}else if(value>arr[mid]){
low = mid+1;
}else{
return mid;
}
}
return -1;//代表没有这个数
}
}