插入排序双arraylist,第一项不会被排序

时间:2014-01-02 02:42:33

标签: java sorting arraylist

排序类中的arraylist插入排序:

public void insertionSort(ArrayList <Double>list){
    double temp;
    int  previousIndex;

    for(int index = 1; index < list.size(); index++){
        temp = list.get(index);
        previousIndex = index - 1;
        while((list.get(previousIndex) > temp) && (previousIndex > 0)){
            list.set((previousIndex+1), list.get(previousIndex));
            previousIndex-=1;
        }
        if(list.get(previousIndex) > temp){
            list.set((previousIndex+1), list.get(previousIndex));
           list.set((previousIndex+1), temp);
        }else{
           list.set((previousIndex+1), temp);
        }
    } 
}

主要课程:

package sorts;

import java.util.*;

public class TestSorts {


public static void displayArrayList(ArrayList <Double> list){
    for (int i=0; i<list.size();i++){
        System.out.print(list.get(i)+" \n");
    }
    System.out.println("\n");       
}

public static void main(String[] args) {
    Scanner in=new Scanner(System.in);
    int numItems,searchNum,location;
    Sorts sort=new Sorts();

    Scanner in=new Scanner(System.in);
    int numItems,searchNum,location;
    Sorts sort=new Sorts();
    System.out.print("Enter the number of elements: ");
    numItems=in.nextInt();

    ArrayList <Double> list=new ArrayList<>();


    for (int i=0;i<numItems;i++){
        list.add((int)100*Math.random());
    }


    System.out.println("Unsorted: ");
    displayArrayList(list);
    sort.insertionSort(list);
    System.out.println("Sorted: ");
    displayArrayList(list);               

  }  
}

现在基本上发生的事情是数字生成正常,并且排序很好,除了它排序时,排序列表中的第一项将是不正确的。如:

未分类:

58.754608713273925 

77.15776272269233 

61.752499151303795 

1.9942069463339207 

55.30460705281677 

78.06371704304172

排序:

58.754608713273925

1.9942069463339207 

55.30460705281677 

61.752499151303795 

77.15776272269233 

78.06371704304172 

所以似乎一切都很好,但是列表中的第一个随机数永远不会被排序,最终会保持与以前完全相同的位置。

2 个答案:

答案 0 :(得分:1)

您的排序例程中

index = 1应为index = 0。目前,您正在跳过列表中的第一个项目,该项目存储在索引零处。

答案 1 :(得分:0)

试试这个:

public static void insertionSort(ArrayList<Double> list) {
        double temp;
        int previousIndex;

        for (int index = 1; index < list.size(); index++) {
            temp = list.get(index);
            previousIndex = index - 1;
            while (previousIndex >= 0 && (list.get(previousIndex) > temp)) {
                list.set((previousIndex + 1), list.get(previousIndex));
                previousIndex -= 1;
            }
            if (previousIndex >= 0 && list.get(previousIndex) > temp) {
                list.set((previousIndex + 1), list.get(previousIndex));
                list.set((previousIndex + 1), temp);
            } else {
                list.set((previousIndex + 1), temp);
            }
        }
    }