以下是使用递归实现整数到序的Java代码:

public class IntegerSort {

    public static void main(String[] args) {
        int num = 123456789;
        int[] sortedArray = sort(num);
        for (int i = 0; i < sortedArray.length; i++) {
            System.out.print(sortedArray[i] + " ");
        }
    }

    public static int[] sort(int num) {
        if (num < 10) {
            return new int[]{num};
        } else {
            int[] sorted = sort(num / 10);
            int[] result = new int[sorted.length + 1];
            int i = 0;
            while (i < sorted.length && sorted[i] < num % 10) {
                result[i] = sorted[i];
                i++;
            }
            result[i] = num % 10;
            while (i < sorted.length) {
                result[i+1] = sorted[i];
                i++;
            }
            return result;
        }
    }
}

首先,在main方法中定义一个整数num,表示要排序的整数。然后,调用sort方法,将返回的数组保存在sortedArray中。最后,遍历sortedArray并打印每个元素。

sort方法中,如果整数num小于10,则表示它只有一位数,直接返回一个只包含它的数组。否则,递归调用sort方法,将整数num除以10后的结果作为参数。返回的数组是已经排好序的,然后将整数num的个位数插入到这个数组中。具体地,我们先定义一个长度为sorted.length + 1的新数组result,然后遍历已排序的数组sorted,将小于个位数的元素复制到result中。接着,将个位数插入到result的第i个位置,然后将剩余的已排序元素复制到result中。最后,返回result数组。

Java 递归实现整数排序算法

原文地址: https://www.cveoy.top/t/topic/j8p5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录