常见算法题

1、冒泡排序

package maopao;

public class Maopao {
    public static void main(String[] args) {
        int[] arr = {1, 32, 12, 43,23}; 
        for(int i=0; i<arr.length-1; i++) {
            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; 
                }
            }
        }
        for(int i: arr) {
            System.out.println(i + " ");
        }
    }
}

结果

1 
12 
23 
32 
43 

2、两个有序数组进行排序,同样有序

    //两个排序数组合并以后进行排序
    public static void method1() {
        int[] num1 = new int[] {
                1, 4, 5,8, 34
        }; 
        int[] num2 = new int[] {
                0, 3, 6, 7,
        }; 
        //变量用于存储两个集合应该被比较的索引
        int a = 0; 
        int b = 0; 
        int[] num3 = new int[num1.length + num2.length]; 
        for(int i=0; i<num3.length; i++) {
            //两个数组都没有遍历完  相互比较谁最小就放入数组  然后将小的放入数组,同时a或者b都要加1
            if(a<num1.length && b<num2.length) {  //两数组都未遍历完,相互比较后加入
                if(num1[a] > num2[b]) {  //当num2数组小的时候
                    num3[i] = num2[b]; 
                    b++; 
                }else {
                    //当num1数组小的时候
                    num3[i] = num1[a]; 
                    a++; 
                }
                //当num2已经遍历完的时候  
            }else if(a<num1.length){  //num2已经遍历完  无需比较  直接将剩余num1加入
                num3[i] = num1[a]; 
                a++; 
                //当num1遍历完的时候 这里做了两个判断  主要是避免不知道哪个长
            }else if(b<num2.length) {  //num1已经遍历完,无需比较,直接将剩余num2加入
                num3[i] = num2[b]; 
                b++; 
            }
        }
        System.out.println("排序后:" + Arrays.toString(num3));
    }

结果

排序后:[0, 1, 3, 4, 5, 6, 7, 8, 34]

3、一个数组的倒序

    public static void method2() {
        int[] b = {1 , 2, 4, 5}; 
        //这里取开头0 取最后一位  start<end  当start超过end  说明已经过了中位数,不用再换位置
        //申明了两个变量   start  end
        for(int start=0, end = b.length-1; start<end; start++, end--) {
            int temp = b[start];   //第一个和最后一个换位置
            b[start] = b[end]; 
            b[end] = temp; 
        }
        for(int i=0; i<b.length; i++) {
            System.out.println(b[i]);
        }
    }

结果

5 4 2 1 

 

原文地址:https://www.cnblogs.com/HelloM/p/14162182.html