如何修复这个冒泡排序程序?

时间:2009-10-31 08:25:32

标签: java sorting bubble-sort

package arraySort;

import java.io.IOException;
import java.io.File;
import java.util.*;

public class openFile {
    int x;
    static int i;
    static int[] myList = {100};

    public static void main(String[] args){
        try{
            File myFile = new File("arraySort.txt");
            Scanner scan = new Scanner(myFile);
            while(scan.hasNext()){                
                myList[i] = scan.nextInt();
                BubbleSort(myList);
                System.out.println(myList[i]);                                
         } 
         catch(IOException e){
             System.out.println("File not found!");
         }
    }
    public static void BubbleSort(int[] x){
        if (x[i] > x[i + 1]){
            int temp;
            temp = x[i];
            x[i] = x[i+1];
            x[i+1] = temp;
        }
    }
}

5 个答案:

答案 0 :(得分:6)

而不是直接给出答案,这里有几个提示:

  1. BubbleSort()

  2. 中没有任何循环
  3. 您应该只调用BubbleSort()一次, 之后您已经读取了文件中的所有数字。意思是,将调用移到while循环之外。

  4. 您永远不会增加变量i,因此您每次只需通过myList[0]循环覆盖while

  5. 数组不可调整大小。如果您尝试分配到myList[1]myList[2],则会收到ArrayIndexOutOfBoundsException错误。有几种方法可以解决这个问题 - 一种方法是将其从int[] myList = {100}更改为ArrayList myList = new ArrayList()。您可以使用myList.add(number)为其添加数字,然后使用myList.get(i)进行查找。

答案 1 :(得分:2)

您的程序有几个问题,而不仅仅与排序部分有关。

static int[] myList = {100};

此行将myList定义为大小为1的数组,其中包含单个元素100。然后,你的主循环是

while(scan.hasNext()) {
    myList[i] = scan.nextInt();
    BubbleSort(myList);
    System.out.println(myList[i]);
}

您不会在此循环中增加i,因此您只需使用从文件中读取的任何值覆盖myList中的单个值。当您的Bubblesort函数尝试访问myList[i+1]时,它会抛出ArrayIndexOutOfBoundsException,因为索引i+1(等于1时没有元素,因为您没有不要增加i)。

一般情况下,特别是初学者,使用ArrayList比使用常规数组更好。此外,您应首先填写数组,并且只有在您尝试对其进行排序时才具有所有元素。最后,最好将变量设为局部而不是类成员。这样会使main函数类似

ArrayList myList = new ArrayList();
while(scan.hasNext()) {
    myList.append(scan.nextInt());
}
Bubblesort(myList);

然后更改Bubblesort以获取ArrayList,然后您还可以使i方法的循环索引Bubblesort成为本地。完成后,您可以使用冒泡排序算法。请记住要小心那里的数组索引,以便永远不会访问数组的边界。

答案 2 :(得分:1)

答案 3 :(得分:0)

改变这个:

 try{
    File myFile = new File("arraySort.txt");
    Scanner scan = new Scanner(myFile);
    while(scan.hasNext()){                
        myList[i] = scan.nextInt();
        BubbleSort(myList);
        System.out.println(myList[i]);
 } 
 catch(IOException e){
     System.out.println("File not found!");
 }

为:

try{
    File myFile = new File("arraySort.txt");
    Scanner scan = new Scanner(myFile);
    while(scan.hasNext()){                
        myList[i] = scan.nextInt();
 } 
 catch(IOException e){
     System.out.println("File not found!");
 }

 BubbleSort(myList);
 System.out.println(myList[i]);

}

根据@Federico

的回答更改排序方法

答案 4 :(得分:0)

完成此作业后,您可能会喜欢Collections.sort():)

http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collections.html#sort%28java.util.List%29

相关问题