java插入排序


public class InsertSort {

private List<Integer> arr;

public List<Integer> getArr() {
return arr;
}

public InsertSort(int size, int valueRange) {
arr = new ArrayList<>();
Random random = new Random();
for (int i = 0; i < size; i++) {
arr.add(Math.abs(random.nextInt()) % valueRange + 1);
}
}

public void insertSort(){
for (int i = 1; i < arr.size(); i++) {
Integer temp = arr.get(i);
if (temp < arr.get(i - 1)) {
arr.remove(i);
for(int j=0;j<i;j++) {
if (arr.get(j) >= temp) {
arr.add(j, temp);
break;
}
}
}
}
}

public static void main(String[] args) {
InsertSort insertSort = new InsertSort(10,100);
System.out.println(insertSort.getArr().toString());
insertSort.insertSort();
System.out.println(insertSort.getArr().toString());
}
}
 
原文地址:https://www.cnblogs.com/zfzf1/p/11655353.html