JAVA interview algorithm question, merge two unordered arrays and sort them from large to small

The algorithm questions I encountered in the interview recently, haha, I have to learn algorithms for beginners in java, although it is not difficult, alas, it is too complicated.

 You can look at the problem and think about how to solve it yourself

Let me show you my solution code

public class demo {
    public static void main (String[] args) {
        int[] a = {1, 3, 4, 5, 6};
        int[] b = {2, 7, 8, 9};
        int[] c = new int[a.length + b.length];
        //循环添加数组内容
        for (int i = 0; i < c.length; i++) {
            if (i < a.length) {
                c[i] = a[i];
            } else {
                c[i] = b[i - a.length];
            }
        }
        System.out.println("合并后");
       /*
        外层循环控制找出的具体最小值的次数,最后一个数据不需要再次比较
         */
        for (int i = 0; i < c.length-1; i++) {
            int minIndex = i;//定义最小值数组索引
            /*
            内层循环通过最小索引的数组值和数组中其他值分别比较,
            若最小索引的值大于比较值,则把比较值的索引赋给最小索引
             */
            for (int j = i+1; j < c.length; j++) {
                if (c[minIndex]>c[j]){
                    minIndex = j;
                }
            }
            /*
            每一轮内部循环获得的分段最小值进行交换,
            把最小值依次赋给外部循环控制的nums数组的每一个索引的值
             */
            int temp = c[minIndex];
            c[minIndex] = c[i];
            c[i] = temp;
            System.out.print(c[i]);
        }
    }
    

}

This is also based on the boss’s post. If you have other solutions, you can share them with me in the comment area.

Screenshot of the output result

 

Guess you like

Origin blog.csdn.net/qq_57484285/article/details/128940396