一、一维数组的排序 – 冒泡排序
口诀:
N个数字来排序
两两相比小靠前
外层循环N-1(一共要排序多少轮)
内层循环N-1-i(参加排序的数量)
public class Test01{
public static void main(String[] args){
int[] arr = {7,9,6,3,5,8};
for(int i = 0;i<arr.length-1;i++){
for(int j = 0;j<arr.length-1-i;j++){
if(arr[j] > arr[j+1]){
int temp = arr[j];
int arr[j] = arr[j+1];
int arr[j+1] = temp;
}
}
}
for(int element : arr){
System.out.println(element);
}
}
}
二、数组的查找 – 现性查找
public class Test02{
public static void main(String[] args){
int[] arr = {6,3,7,5,2,1};
int num = 6;
for(int i = 0;i<arr.length;i++){
if(num == arr[i]){
System.out.println("元素查找到了,下标为:" + i);
}
}
}
}
三、数组的查找 – 二分法/二叉查找
import java.util.Arrays;
public class Test03{
/**
注意:二分法查找之前必须先排序!!!
*/
public static void main(String[] args){
int[] arr = {6,3,7,5,2,1};
//排序 -- 1,2,3,5,6,7
Arrays.sort(arr);
int num = 6;
int start = 0;
int end = arr.length-1;
while(start <= end){
int mid = (start+end)/2;
if(num < arr[mid]){
end = mid-1;
}else if(num > arr[mid]){
start = mid+1;
}else{
System.out.println("元素查找到了,下标为:" + mid);
break;
}
}
}
}