冒泡排序法、查找

案例:int[] arr ={34,27,13,8,66,45,9};

 1 public class Bubblesort{
 2     public static void main (String[] args){
 3         /*
 4         冒泡排序法:
 5         */
 6       int[] arr ={34,27,13,8,66,45,9};
 7         int temp = 0;
 8         //外层循环是6次
 9         for (int i= 0; i < 6 ;i++ ) {
10           for (int j = 0;j < 6-i ;j++ ) {//j代表比较的次数,6-i表示总的需要比较次数-当前循环的次数
11        //如果前面的数大于后面的数,就进行交换
12               if (arr[j]>arr[j+1]) {
13                temp = arr[j];
14             arr[j] =arr[j+1];
15             arr[j+1] =temp;
16            }
17             
18         } 
19         System.out.println("\n"+"第"+(i+1)+"轮排序");
20         for (int j = 0;j<arr.length ;j++ ) {
21             System.out.print(arr[j]+"\t");
22         }
23         }
24 
25     }
26 }

 案例2:查找

请对一个有序数组进行查找{"数学","英语","化学","物理","语文"},输入一个数,看该数据是否存在这个数组里面,并且求出下标,如果没有,就提示没有这个数?

 

 1 import java .util.Scanner;
 2 public class Find{
 3     public static void main(String[] args){
 4         /*
 5          查找
 6         */
 7         String [] name ={"数学","英语","化学","物理","语文"};
 8         Scanner myscanner = new Scanner(System.in); 
 9         System.out.println("请输入你想学的科目");
10         //定义从键盘中存放的变量;
11         String school= myscanner.next();
12         int index = -1;
13         //从数组arr中开始遍历循环
14         for (int  i =0 ;i<name.length ;i++ ) {
15             //判断输入的字符school是否与arr数组中的内容相一致,用方法equals,
16             if (school.equals(name[i])) {//如果输入的school字符与arr数组中的元素一致
17                 System.out.println("恭喜你找到"+school);
18                 System.out.println("对应下标为" + i);
19                 //把i保存到index
20                 index = i;
21                 break;
22             }
23         }
24         if (index==-1) {
25             System.out.println("抱歉,没有找到"+school);
26         }
27     }
28 }

 

上一篇:SpringXML的beans标签后的一串网址相关的属性有什么用


下一篇:Spring项目卡在parsed mapper file: */*.xml