冒泡排序和二分法查找
//------------冒泡排序----------------------------
int score []={12,42,34,3,2,8,59,50,48};
for (int i = 0; i < score.length-1; i++) {
for (int j = 0; j < score.length-i-1; j++) {
if (score[j] <score[j+1]) {
int temp=score[j];
score[j]=score[j+1];
score[j+1]=temp;
}
}
System.out.print("第" + (i + 1) + "次排序结果:");
for(int a=0;a<score.length;a++){
System.out.println(score[a]+"\t");
}
System.out.println("");
}
System.out.println("最终排序结果:");
for (int a = 0; a < score.length; a++) {
System.out.println(score[a]+"\t");
}
//--------------二分法查找-----------------------
package com.example.erfen;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//定义一个有序的数组(二分法的前提必须是一组有序的数据)
int [] arr=new int []{0,2,3,5,7,8,9,12,15};
//定义要查找的数
int key=6;
//定义一个方法用于返回查询出来的数
int result=this.bnum(arr,key);
//答应
System.out.println("下标为:"+result+"的数是"+key);
}
private int bnum(int[] arr, int key) {
//定义开头下标
int first=0;
//定义最后一个的下标
int last=arr.length-1;
//当开头的小标小于最后的下标的时候循环
while (first<=last) {
//获得中间的下标
int mobile=(first+last)/2;
Log.i("我是中间下标值:", mobile+"");
Log.i("我是中间值:", arr[mobile]+"");
//如果中间下标对应的值等于key
if (arr[mobile]==key) {
//返回下标为第mobile的就是9
return mobile;
//中间下标对应的值小于key值,说明key位于右边
}else if (arr[mobile]<key) {
first=mobile+1;
//中间下标对应的值小于key值,说明key位于左边
}else if (arr[mobile]>key) {
last=mobile-1;
}
}
Toast.makeText(MainActivity.this, "bb", 0).show();
return -1;
}
}