直接插入排序算法:ArrayList实现和数组实现

直接插入排序算法思想:

  • 排序区间R[1..n]
  • 在排序的过程中,整个排序区间被分为两个子区间: 有序区R[ 1 ... i-1 ]和无序区R[ i ... n ]
  • 共进行n-1趟排序,每趟排序都是把无序区的第一条记录Ri插到有序区的合适位置上。

ArrayList实现:

import java.util.ArrayList;
import java.util.Random;

public class Charupaixu {

ArrayList<Integer> al;

public Charupaixu(int num, int bound) {
    al = new ArrayList<>(num);
    // 创建一个随机数生成器
    Random rand = new Random();
    // 添加1-100的随机整数
    for (int i = 0; i < num; i++) {
        al.add(new Integer(Math.abs(rand.nextInt(bound))));
    }
    System.out.println("The ArrayList Sort Before:\n" + al);
}

public void ZJCRSortIt() {
    System.out.println("Sorting :");
    Integer tempInt;

    for (int i = 1; i < al.size(); i++) {
        // 将a[i]插入到a[i-1] a[i-2] a[i-3] ... 中
        for (int j = i; j > 0 && (al.get(j) < al.get(j - 1)); j--) {
            tempInt = al.remove(j);
            al.add(j - 1, tempInt);
            System.out.println(al);
        }
    }
}

public static void main(String[] args) {
    Charupaixu cr = new Charupaixu(10, 100);
    cr.ZJCRSortIt();
}

}

Output:

The ArrayList Sort Before:
[10, 75, 61, 50, 17, 60, 19, 7, 73, 87]
Sorting :
[10, 75, 61, 50, 17, 60, 19, 7, 73, 87]
[10, 61, 75, 50, 17, 60, 19, 7, 73, 87]
[10, 50, 61, 75, 17, 60, 19, 7, 73, 87]
[10, 17, 50, 61, 75, 60, 19, 7, 73, 87]
[10, 17, 50, 60, 61, 75, 19, 7, 73, 87]
[10, 17, 19, 50, 60, 61, 75, 7, 73, 87]
[7, 10, 17, 19, 50, 60, 61, 75, 73, 87]
[7, 10, 17, 19, 50, 60, 61, 73, 75, 87]
[7, 10, 17, 19, 50, 60, 61, 73, 75, 87]

数组实现:

int[] a={ 50, 15, 18, 8, 40, 51, 60, 1, 1, 20, 15 };
        System.out.println("The ArrayList Before Sort is:");
        for (int k = 0; k < a.length; k++) {
            System.out.print(a[k]+", ");
        }

        System.out.println("\nSorting:");
        
        for(int i = 1;i<a.length;i++){
            
            int temp = a[i];
            int j;
            //在内层for循环外面声明循环变量j,j能取到j不满足循环条件的那个值。
            
            for (j = i; (j >0) && (a[j-1] > temp); j--) {
                a[j]=a[j-1];
            }
            
            a[j]=temp;
            
            for (int k = 0; k < a.length; k++) {
                System.out.print(a[k]+", ");
            }
            
            System.out.println();
        }
        
        
Output:

The ArrayList Before Sort is:
50, 15, 18, 8, 40, 51, 60, 1, 1, 20, 15, 
Sorting:
15, 50, 18, 8, 40, 51, 60, 1, 1, 20, 15, 
15, 18, 50, 8, 40, 51, 60, 1, 1, 20, 15, 
8, 15, 18, 50, 40, 51, 60, 1, 1, 20, 15, 
8, 15, 18, 40, 50, 51, 60, 1, 1, 20, 15, 
8, 15, 18, 40, 50, 51, 60, 1, 1, 20, 15, 
8, 15, 18, 40, 50, 51, 60, 1, 1, 20, 15, 
1, 8, 15, 18, 40, 50, 51, 60, 1, 20, 15, 
1, 1, 8, 15, 18, 40, 50, 51, 60, 20, 15, 
1, 1, 8, 15, 18, 20, 40, 50, 51, 60, 15, 
1, 1, 8, 15, 15, 18, 20, 40, 50, 51, 60,

相关推荐