java basic algorithm sorting

1. Choose Sort

import java.util.Arrays;

public class SelectSort {
    // 选择排序:每一轮选择最小元素交换到未排定部分的开头
    public int[] sortArray(int[] nums) {
        int len = nums.length;
        for (int i = 0; i < len - 1; i++) {
            int minIndex = i;
            for (int j = i + 1; j < len; j++) {
                if (nums[j] < nums[minIndex]) {
                    minIndex = j;
                }
            }
            swap(nums, i, minIndex);

        }
        return nums;
    }

    private void swap(int[] nums, int index1, int index2) {
        int temp = nums[index1];
        nums[index1] = nums[index2];
        nums[index2] = temp;

    }

    public static void main(String[] args) {
        int[] nums= {5,1,9,6,2,7,3,8};
        SelectSort solution = new SelectSort();
        int[] res = solution.sortArray(nums);
        System.out.println(Arrays.toString(res));

    }
}

2. Insert Sort

public class InsertSort{
public int[] sortArray(int[] nums) {
        int len = nums.length;
        // 循环不变量:将 nums[i] 插入到区间 [0, i) 使之成为有序数组
        for (int i = 1; i < len; i++) {
            // 先暂存这个元素,然后之前元素逐个后移,留出空位
            int temp = nums[i];
            int j = i;
            // 注意边界 j > 0
            while (j > 0 && nums[j - 1] > temp) {
                nums[j] = nums[j - 1];
                j--;
            }
            nums[j] = temp;
        }
        return nums;
    }
}

Guess you like

Origin www.cnblogs.com/gongcheng-/p/12683388.html