插入排序(两个for循环实现)---java

项目思路:

1将数组分为两部分看待,一部分是排序后的数组,一部分是要插入到排序后数组的元素。默认按从小到大排序

2将要插入的数据x,以其前面的有序数据一次进行比较,如果有序数据大于数据x,则有序数据一次后移一位,空出一个位置使x插入,这个位置前面的数据都比x小,后面的都比x大。

注:一次后移比较重要


gitee地址


项目代码:

插入排序函数sort(int[] array)

注解:index是用来记录要插入位置的下标。内层循环是后移

public static void sort(int[] array) {
        int temp;//保存要插入变量的值
        int index;//记录插入地方的下标
        for (int i = 1; i < array.length; i++) {
            index = i;
            temp = array[i];
            for (int j = i; j > 0; j--) {
                if (temp < array[j - 1]) {
                    array[j] = array[j - 1];
                    index = j - 1;
                }


            }
            array[index] = temp;
        }
    }

总体代码

注解:主要理解下sort函数就好了

package DataStructures.sort;

/**
 * @author :ALi
 * @date :Created in 2021/11/8 8:59
 * @description:插入排序
 * @modified By:
 * @version: $
 */
public class InsertSort {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 5, 4, -1};
        sort(array);
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + " ");
        }

    }

    public static void sort(int[] array) {
        int temp;//保存要插入变量的值
        int index;//记录插入地方的下标
        for (int i = 1; i < array.length; i++) {
            index = i;
            temp = array[i];
            for (int j = i; j > 0; j--) {
                if (temp < array[j - 1]) {
                    array[j] = array[j - 1];
                    index = j - 1;
                }


            }
            array[index] = temp;
        }
    }

}
经验分享 程序员 微信小程序 职场和发展