Java 什么';这个排序算法怎么了?(越界例外)
错误如下:Java 什么';这个排序算法怎么了?(越界例外),java,quicksort,Java,Quicksort,错误如下: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 at QuickSort.partition(QuickSort.java:39) at QuickSort.quickSort(QuickSort.java:19) at QuickSort.sort(QuickSort.java:13) at QuickSortTest.main(QuickSortTest
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at QuickSort.partition(QuickSort.java:39)
at QuickSort.quickSort(QuickSort.java:19)
at QuickSort.sort(QuickSort.java:13)
at QuickSortTest.main(QuickSortTest.java:15)
我不明白为什么这里会越界
if (orig[q] >= orig[q - 1]) {
我测试这个是为了好玩。我知道使用这种枢轴可能没有任何作用。我试图从原始长度的->原始长度/sqrt*log2(原始长度)和最接近该最大值33%的值之间的间隔中找到数组中的最大值,并将其设置为我的轴。然后通常进行快速排序
import java.lang.*;
public class QuickSort {
int[] ary;
public QuickSort(int[] num) {
ary = num;
}
public int[] sort() {
int low = 0;
int high = ary.length - 1;
quickSort(ary, low, high);
return ary;
}
private void quickSort(int[] orig, int low, int high) {
int save = partition(orig, low, high);
if (low < (save - 1)) {
quickSort(orig, low, (save - 1));
}
if (save < high) {
quickSort(orig, save, high);
}
}
private int partition(int[] orig, int low, int high) {
int i = low;
int j = high;
int temp;
int large = 0;
int swapspot = 0;
int need = orig.length / ((int) (Math.sqrt(ary.length)) * ((int) (Math.log(ary.length) / (Math.log(2)))));
for (int q = need; q > need / 2 - 1; q--) {
if (orig[q] >= orig[q - 1]) {
orig[q] = large;
} else {
orig[q - 1] = large;
}
if (q == need / 2) {
int saver = (int) (large * .33);
for (int h = 0; h < orig.length; h++) {
if (orig[h] >= saver) {
swapspot = orig[h];
}
}
}
}
while (i <= j) {
while (orig[i] < swapspot) {
i++;
}
while (orig[j] > swapspot) {
j--;
}
if (i <= j) {
temp = orig[i];
orig[i] = orig[j];
orig[j] = temp;
i++;
j--;
}
}
return i;
}
}
import java.lang.*;
公共类快速排序{
整数[]元;
公共快速排序(int[]num){
ary=num;
}
公共int[]排序(){
int低=0;
int high=ary.length-1;
快速排序(ary、低、高);
回归分析;
}
专用void快速排序(int[]原始、int低、int高){
int save=分区(原始、低、高);
如果(低<(保存-1)){
快速排序(原始,低,(保存-1));
}
如果(保存<高){
快速排序(原始、保存、高);
}
}
私有int分区(int[]原始,int低,int高){
int i=低;
int j=高;
内部温度;
int-large=0;
int-swapspot=0;
int need=orig.length/((int)(Math.sqrt(ari.length))*((int)(Math.log(ari.length)/(Math.log(2 '));
对于(int q=need;q>need/2-1;q--){
if(orig[q]>=orig[q-1]){
orig[q]=大型;
}否则{
orig[q-1]=大型;
}
如果(q==需要/2){
int saver=(int)(大*.33);
对于(int h=0;h=saver){
swapspot=原始[h];
}
}
}
}
而(我是斯瓦普波特){
j--;
}
如果(i只看你问题的这两行:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
if (orig[q] >= orig[q - 1]) {
我可以告诉你q是0,显然没有原点[-1]
更新,由@kaan yılmaz添加:
更多解释(实际上不需要,因为答案已经足够好了,但是你问的是编程的基础知识)
在循环开始时,然后您要分配
q=-1
这是不可能发生的,因为您的CPU无法达到oriq[-1],因为您无法计算像-1,0,1,2…这样的苹果数。您看到了什么错误?您想让我们猜测什么“编译不正确”意思是?添加更多关于错误是什么以及您认为错误是什么的信息,或者此问题可能会被删除。您是否使用调试器查看q值有多低(或需要)去?如果你有一个新问题,因为一个新问题,然后创建一个新的帖子,而不是改变这个问题并使现有的答案无效。哎呀。愚蠢的错误。我已经更新了它,但我仍然有这个问题。你想让我通过在注释中添加下一个错误消息一行一行地修复你的代码吗?我也抛出了一个错误“StackOverFlow.com错误”。如果“need/2-1”可以为零,则为True。
q=0
q=-1