一、冒泡排序
像冒泡泡一样,大的往上冒泡泡。。。
相邻的元素比较大小,如果前一个元素比后一个元素大,则交换位置
int[] score = {1, 2, 3, 4, 5,1,3,32,4,3,4,3,43,432};
System.out.println("通过冒泡排序方法对数组进行排序:");
for(int i=0;i<score.length-1;i++){
for(int j=i+1;j<score.length;j++){
if(score[j] > score[i] ){//如果后面的大于前面的,做一个交换
int temp = score[j];
score[j] = score[i];
score[i] = temp;
}
}
}
for (int i : score) {
System.out.println(" " +i );
}
二、二分查找
int[] score = {1,2,3,4,5,6,8,9,10,11};
int value = 12;
int index = -1;
int start = 0;
int end = score.length-1;
while(start <= end){
int mid = (start + end) >>> 1;
if(value == score[mid]){
index = mid;
break;
}else if(value < score[mid]){
end = mid-1;
}else if(value > score[mid]){
start = mid+1;
}
}
if(index == -1){
System.out.println("未找到");
}else {
System.out.println("index = " + index);
}