这是从网站上获取的Heap Sort的修改后的实现。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class HeapSort
{
static int heapsize;
public static void main(String args[])
{
Vector<Integer> container = new Vector<Integer>(); // container used to store txt file integers
Scanner myScanner = new Scanner("foo"); // variable used to read file
String userinput="data1.txt";
try
{
//open filename
//got problem , must think how to do relative path instead of absolute path
File inputfile = new File("C:\\Users\\8382c\\workspace\\AdvanceAlgorithmA3_Heapsort\\src\\" + userinput);
myScanner = new Scanner(inputfile);
}
catch(FileNotFoundException e)
{
System.out.println("File cant be found");
}
String line = myScanner.nextLine(); //read 1st line which contains the number of numbers to be sorted
while (myScanner.hasNext())
{
container.add(myScanner.nextInt());
}
heapsize = container.size();
System.out.println(heapsize);
sort(container);
int x =10;
/*for (int i=0 ; i < container.size() ; i ++)
{
System.out.println(container.get(i));
}*/
//http://www.sanfoundry.com/java-program-implement-heap-sort/
}
public static void swap(Vector<Integer> container, int i, int j)
{
/*int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;*/
int tmp = container.get(i);
container.set(i, container.get(j));
container.set(j, tmp);
}
public static void maxheap(Vector<Integer> container, int i) //ensure max number is the parent
{
int left = 2*i ;
int right = 2*i + 1;
int max = i;
if (left <= heapsize && container.get(left) > container.get(i));
max = left;
if (right <= heapsize && container.get(right) > container.get(max))
max = right;
if (max != i)
{
swap(container, i, max);
maxheap(container, max);
}
}
public static void heapify(Vector<Integer> container) //built a heap
{
heapsize = container.size()-1;
for (int i = heapsize/2; i >= 0; i--)
maxheap(container, i);
}
public static void sort(Vector<Integer> container)
{
heapify(container);
for (int i = heapsize; i > 0; i--)
{
swap(container,0, i);
heapsize = heapsize-1;
maxheap(container, 0);
}
}
}
我已经阅读了text file(忽略txt文件的第1行,它表示条目数),其中包含10000个数字到Vector中并尝试对其进行排序但是出现以下错误
java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 19998
我的调试器无法正常工作,因为每次我跳过函数max heap
时,我都会得到尚未解析的source not found。
我不明白数组越界错误的起源,我已经查看了过去2小时的实现代码并且无法找到任何问题,有人可以告诉我我的代码有什么问题吗?< / p>
答案 0 :(得分:3)
此行末尾有分号:
if (left <= heapsize && container.get(left) > container.get(i));
这意味着下一行始终在运行,而不仅仅是条件为真。拿掉分号,你就好了!