Java array exercise summary-28 days study notes

Array exercises

\1. Use bubble sort to realize the following array sorting from small to large.

int[] arr = new int[]{34,5,22,-98,6,-76,0,-3};

\2. How to reverse the above array. Please code implementation

\3. Copy the above array to get a new array

\4. Use linear search to find whether 22 exists from the above array. Exist, return the index of the location. If it does not exist, a prompt message will be output.

\5. What are the common exceptions in the array? Please give an example

package com.oop.Demo07;

import java.util.Arrays;

public class Demo01 {
    public static void main(String[] args) {

//        1.  使用冒泡排序,实现如下的数组从小到大排序。
           int[] arr = new int[]{34,5,22,-98,6,-76,0,-3};
            //通过遍历比较大小交换两个数的位置
           for (int i = 0; i < arr.length-1; i++) {
              boolean flag = true;
               for (int j = 0; j < arr.length-1-i; j++) {
                   if (arr[j] > arr[j+1]) {
                       int temp = arr[j];
                         arr[j] = arr[j+1];
                         arr[j+1] = temp;
                         flag = false;
                   }
               }
           }
           //输出数组
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+"\t");
        }
        System.out.println();

//        2.  如何反转上面的数组。请代码实现
         //确定第一个数和最后一个数  i < j 不然会导致赋值重复
        for (int i = 0,j = arr.length-1; i < j; i++,j--) {
            //通过temp和交换
            int temp  = arr[i];
               arr[i] = arr[j];
               arr[j] = temp;
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+"\t");
        }
        System.out.println();
//        3. 复制上述数组,得到一个新的数组
        int[] arr2 = new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            arr2[i] = arr[i];
        }
        System.out.println(Arrays.toString(arr2));
//        4. 使用线性查找,从上述数组中查找22是否存在。存在,返回所在位置的索引。不存在,输出提示信息。
        int[] arr3 = new int[]{-98,-76,-3,0,5,6,22,34};//需要排好序的数组
          //定义首位,末位,和需要查找的数
        int dest = 22;
        int first = 0;
        int end = arr3.length-1;
        //布尔值判断
        boolean flag = true;
        while (first <= end){
            //定义一个中间变量
            int mid = (first + end) / 2;
            if(dest == arr3[mid]){
                System.out.println("找到了元素的位置"+mid);
                flag = false;
                break;
                //首位比中间位小
            }else if(dest < arr3[mid]){
                end = mid - 1; //最后一位中间值减一
            }else{
                first = mid + 1;
            }

            }
            if(flag) {
            System.out.println("没有找到");
        }

//        5. 数组中常见的异常有哪些?请举例说明
        //空指针异常
        //越界

    }
}

Guess you like

Origin blog.csdn.net/yibai_/article/details/115287298