Arraylist 插入排序

Arraylist Insertion-Sort

如何使用插入对数组列表进行排序?这是我的数组列表,它充满了随机整数:

ArrayList<Integer> oh = new ArrayList<Integer>();
Random random = new Random();

for (int i = 0; i < 100; i++)
{
    oh.add(random.nextInt());
}
import java.util.ArrayList;

public class InsertionSort {    

    private static ArrayList<Integer> inputArray = new ArrayList<Integer>();

    public static ArrayList<Integer> getInputArray() {
        return inputArray;
    }


    public InsertionSort(ArrayList<Integer> inputArray){
        InsertionSort.inputArray = inputArray;
    }

    public void sortGivenArray(){                   
        for(int i=1;i<inputArray.size();i++){

            int key = inputArray.get(i);

            for(int j= i-1;j>=0;j--){
                if(key<inputArray.get(j)){

                    inputArray.set(j+1,inputArray.get(j));


                    if(j==0){
                        inputArray.set(0, key);
                    }
                }else{

                    inputArray.set(j+1,key);
                    break; 
                }
            }
        }       
    }
}
import java.util.ArrayList;

import daa.InsertionSort;


public class MainPractise implements Cloneable {    

    public static void main(String[] args) {


        ArrayList<Integer> unsortedArray = new ArrayList<Integer>();

        unsortedArray.add(8);
        unsortedArray.add(7);
        unsortedArray.add(6);
        unsortedArray.add(5);
        unsortedArray.add(4);
        unsortedArray.add(0);
        unsortedArray.add(2);   
        InsertionSort is = new InsertionSort(unsortedArray);

        System.out.println("---------Initial Unsorted Array---------");
        for(int i:InsertionSort.getInputArray()){
            System.out.print(i+" ");
        }

        is.sortGivenArray();

        System.out.println("\n------------Sorted Array------------");
        for(int i:InsertionSort.getInputArray()){
            System.out.print(i+" ");
        }
        }
}

试试这个可以帮助你解决问题,用插入排序对 Arraylist 进行排序。

public static void main(String args[]) {

    ArrayList<Integer> oh = new ArrayList<Integer>();
    Random random = new Random();

    for (int i = 0; i < 100; i++) {
        oh.add(random.nextInt());
    }
    int[] elementlist = new int[oh.size()];
    Iterator<Integer> iter = oh.iterator();
    for (int j = 0; iter.hasNext(); j++) {
        elementlist[j] = iter.next();
    }

    int[] list = insertionSort(elementlist);
    for (Integer in : list) {
        System.out.println(in);
    }
}

public static int[] insertionSort(int[] list) {
    for (int i = 1; i < list.length; i++) {
        int next = list[i];
        // find the insertion location while moving all larger element up
        int j = i;
        while (j > 0 && list[j - 1] > next) {
            list[j] = list[j - 1];
            j--;
        }
        // insert the element
        list[j] = next;
    }
    return list;
}

有关详细信息,请进入 link