双重for循环实现插入排序

杀马特。学长 韩版系。学妹 提交于 2019-12-12 13:48:38
import java.util.Arrays;

public class InsertionSort {

    public static void main(String[] args) {
        int[] array = new int[6];
        for (int i = 0; i < 6; i++) {
            array[i] = (int) (Math.random() * 100);
        }
        System.out.println("待排序的数据为:" + Arrays.toString(array));
        System.out.println("开始排序*********");
        insertionSort(array);
        System.out.println("排序过后的数据为:" + Arrays.toString(array));
    }

    public static void insertionSort(int[] array) {
        int len = array.length;
        int temp = 0;
        for (int i = 1; i < len; i++) {
            temp = array[i];    //保存当前需要插入的值
            for (int j = i - 1; j >= 0; j--) {
                if (temp < array[j]) {
                    array[j + 1] = array[j];
                    if (j == 0) {    //比所有数据都小,放在首位
                        array[0] = temp;
                    }
                } else {
                    array[j + 1] = temp;
                    break;
                }
            }
        }
    }

}

在这里插入图片描述

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!