数组常见操作
数组的定义
- int[] arr = new int[5];
- int[] arr = new int[]{1,2,3,4}
- int[] arr = {1,2,3,4}
取数组中的最值
public static void main(String[] args) {
int[] va = {45,7,67,87,98,0,45,78,100};
int tmp = va[0];
for(int i=1;i<va.length;i++){
if(tmp<va[i]){
tmp = va[i];
i++;
}
}
System.out.println(tmp); //最大值
}
选择排序
public static void main(String[] args) {
int[] va = {45,7,67,87,98,0,45,78,100};
int tmp=va[0];
for(int i=0;i<va.length-1;i++){
for(int y=i+1;y<va.length;y++){
if(va[i]>va[y]){
tmp = va[i];
va[i] = va[y];
va[y] = tmp;
}
}
}
for(int i:va){
System.out.print(i);
System.out.print(" ");
}
}
冒泡排序
public static void main(String[] args) {
int[] va = {45,7,67,87,98,0,45,78,100};
int tmp=va[0];
for(int i=0;i<va.length-1;i++){
for(int y=0;y<va.length-1-i;y++){
if(va[y] > va[y+1]){
tmp = va[y];
va[y] = va[y+1];
va[y+1] = tmp;
}
}
}
for(int i:va){
System.out.print(i);
System.out.print(" ");
}
}
二分法查找
public static void main(String[] args) {
int[] arr = {1,2,56,78,98,101,120};
System.out.println(halfSearch(arr,120));
}
public static int halfSearch(int[] arr,int key){
int min,mid,max;
min = 0;
max= arr.length-1;
mid = (min+max)/2;
while(arr[mid]!=key){
if(arr[mid]>key){
max = mid-1;
}else if(arr[mid]<key){
min = mid+1;
}
if(max<min){
return -1;
}
mid = (min+max)/2;
}
return mid;
}