常见排序算法Java版(待续)

  1. 冒泡排序O(n^2)

    public class Main {
        public static void main(String[] args) {
            Random random = new Random();
            int[] nums = new int[]{random.nextInt(100), random.nextInt(100), random.nextInt(100), random.nextInt(100), random.nextInt(100), random.nextInt(100)};
            for (int i = nums.length - 1; i >= 0; i--) {
                for (int j = 0; j < i; j++) {
                    if (nums[j] > nums[j + 1]) {
                        int temp = nums[j];
                        nums[j] = nums[j + 1];
                        nums[j + 1] = temp;
                    }
                }
            }
            for (int num : nums) {
                System.out.print(num + " ");
            }
        }
    }
    

    常见排序算法Java版(待续)_第1张图片

  2. 选择排序O(n^2),

    public class Main {
        public static void main(String[] args) {
            Random random = new Random();
            int[] nums = new int[]{random.nextInt(100), random.nextInt(100), random.nextInt(100), random.nextInt(100), random.nextInt(100), random.nextInt(100)};
            int index;
            for (int i = 0; i < nums.length; i++) {
                index = i;//每一轮记录最小值的索引
                for (int j = i + 1; j < nums.length; j++) {
                    if (nums[j] < nums[index]) {
                        index = j;
                    }
                }
                if (index != i) {
                    int temp = nums[i];
                    nums[i] = nums[index];
                    nums[index] = temp;
                }
            }
            for (int num : nums) {
                System.out.print(num + " ");
            }
        }
    }
    

    常见排序算法Java版(待续)_第2张图片

  3. 插入排序O(n^2)

    public class Main {
        public static void main(String[] args) {
            Random random = new Random();
            int[] nums = new int[]{random.nextInt(100), random.nextInt(100), random.nextInt(100), random.nextInt(100), random.nextInt(100), random.nextInt(100)};
            int index;
            for (int i = 1; i < nums.length; i++) {
                int rec = nums[i];
                index = i;
                for (int j = i - 1; j >= 0; j--) {
                    if (nums[j] > rec) {
                        nums[index] = nums[j];
                        index = j;
                    } else {
                        break;
                    }
                }
                nums[index] = rec;
            }
            for (int num : nums) {
                System.out.print(num + " ");
            }
        }
    }
    

    常见排序算法Java版(待续)_第3张图片

你可能感兴趣的:(排序算法,java,算法)