int min 不能赋值为0,应该赋值为数组的第一个值,为scores【0】,否则在比较中没有小于0的价格则最终输出的min为0。
途中的scores.length应该换位scores.length-1,否则将会造成下标越界。
2.选择结构以及二分查找法
public class Test1001 {
public static void main(String[] args) {
int[] scores = {4,7,3,9,1};
int min = -1;//最小值下标
//外层:比较几轮
for(int i = 0;iscores[j]) {//如果为降序将>改为<
min=j;
}
}
//如果min值发生了变化,则说明发现了更小的值,则将当前值和更小的值进行交换,保证小的值放在数组前面。
if(min!=i) {
int temp =scores[min];
scores[min]=scores[i];
scores[i]=temp;
}
}
//输出排序后的数组
for(int score:scores) {
System.out.print(score+" ");
}
}
}
二分查找法
使用二分查找法必须是一个有序的数组
二分查找法步骤(升序数组)
(1)找到数组中间位置的值,并存放在一个变量temp中
(2)需要查找到值key,拿key和temp比较
(3)如果key>temp,则把数组的中间位置作为下一次计算的起点位置,重复步骤1和2
(4)如果key (5)如果key=temp,返回中间位置下标(元素),完成查找
public class Test1002 {
public static void main(String[] args) {
int[]arr = {0,1,2,3,4,5,6,7,8,9};
int shu =10;//要查找的数字
int start =0;//开始查找的下标
int end = arr.length-1;//结束的下标
int mid =-1;//中间位置的下标
boolean flag = false;//标记是否找到
do {
mid= (start+end)/2;
if(arr[mid] == shu) {
System.out.println("找到了下标是"+mid);
flag =true;
break;
}else if(arr[mid]>shu) {//中间数大于要找到数字
end = mid-1;//从左边开始找
}else {//中间数小于要找到数字
start = mid+1;//从右边开始找
}
}while(start<=end);
if(flag ==false) {
System.out.println("没有找到");
}
}
}
}
}while(start<=end);
if(flag ==false) {
System.out.println("没有找到");
}
}
}



