我知道合并排序是如何工作的,但我一直在找到一个未找到类的定义。
我的代码是:
/*
* Merge Sort Implementation
*/
public class MergeSort {
private int[] array;
private int length;
private int[] tempArray;
public void MergeSort(){}
public static void main(String args[])
{
int[] itemsToSort = {1,5,3,6,7,3,7,1,2};
MergeSort ms = new MergeSort();
ms.sort(itemsToSort);
for (int i: itemsToSort){
System.out.print(i);
System.out.print(" ");
}
}
public void sort( int arr[] )
{
this.array = arr;
this.length = arr.length;
this.tempArray = new int[this.length];
sort(0, this.length -1);
}
private void sort ( int lowerBounds, int upperBounds)
{
if (lowerBounds < upperBounds)
{
int center = (upperBounds + lowerBounds)/2 + lowerBounds;
sort(lowerBounds, center);
sort(center + 1, upperBounds);
merge(lowerBounds,center, upperBounds);
}
}
private void merge ( int lowerBounds, int center, int upperBounds)
{
for (int i = lowerBounds; i < upperBounds; i++)
{
this.tempArray[i] = this.array[i];
}
int i = lowerBounds;
int j = center + 1;
int k = upperBounds;
while(i <= center && j <= upperBounds)
{
if (this.tempArray[i] <= this.tempArray[j])
{
this.array[k] = this.tempArray[i];
i++;
}
else
{
this.array[k] = this.tempArray[j];
j++;
}
k++;
}
while ( i <= center )
{
this.array[k] = this.tempArray[i];
k++;
i++;
}
}
}
最初,我想把MergeSort的存根放入解决它,但我没有解决它,所以我要删除它。
要运行我的程序并收到错误,我将使用终端运行。
javac MergeSort.java
java MergeSort.o
确切的错误是:
[freaper@www java]$ javac MergeSort.java
[freaper@www java]$ java MergeSort.o
Exception in thread "main" java.lang.NoClassDefFoundError: MergeSort/o
Caused by: java.lang.ClassNotFoundException: MergeSort.o
at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:323)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:268)
Could not find the main class: MergeSort.o. Program will exit.
答案 0 :(得分:3)
运行文件时只需要类名。
java MergeSort
将.o
添加到它的末尾对你没有任何好处。
注意:编译类时,Java会生成.class
个类。在这种情况下,它会生成MergeSort.class
。然后,您只想使用不带后缀的文件名在Java上下文中执行,因此您使用java MergeSort
。
答案 1 :(得分:1)
像Makoto所说,你不需要.o
java MergeSort
我运行程序并在sort(lowerBounds, center);
行上从此函数获得了stackoverflow。
private void sort ( int lowerBounds, int upperBounds)
{
if (lowerBounds < upperBounds)
{
int center = (upperBounds + lowerBounds)/2 + lowerBounds;
sort(lowerBounds, center);
sort(center + 1, upperBounds);
merge(lowerBounds,center, upperBounds);
}
}
尝试添加一些调试来查找问题。请记住,您正在使用递归但尚未在排序上设置基本案例。
private void sort(int lowerBounds, int upperBounds) {
if (lowerBounds < upperBounds) {
System.out.println("Lower " + lowerBounds + "\tUpper " + upperBounds);
int center = (upperBounds + lowerBounds) / 2 + lowerBounds;
sort(lowerBounds, center);
sort(center + 1, upperBounds);
merge(lowerBounds, center, upperBounds);
}
}