1.查找数组中的最大元素
import java.util.Arrays;
public class testDemo {
public static void findMax(int[] arr){
int max = arr[0];
for (int i = 1; i <arr.length ; i++) {
if(arr[i]>max){
max = arr[i];
}
}
return max;
}
public static void main(String[] args) {
int[] arr = {1,5,3,7,6};
findMax(arr);
System.out.println(Arrays.toString(arr));
}
}
顺序查找
public static void findNum(int[] arr,int num){
for (int i = 0; i <arr.length ; i++) {
if (arr[i]== num){
return i;
}
}
return -1;
}
}
数组的逆序
public static void reverse(int[] arr) {
int i=0;
int j=arr.length-1;
while (i<j){
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
}
二分查找
public static int binarySearch(int[] arr,int key) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == key) {
return mid;
} else if (arr[mid] > key) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
奇数在右边,偶数在左边
public static void func(int[] arr){
int i=0;
int j = arr.length-1;
while (i<j){
while (i<j && arr[i]%2==0){
i++;
}
while(i<j && arr[j] %2!=0){
j--;
}
return;
}else {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}