[英]I'm not sure what's wrong with my partition function
Eclipse不斷告訴我,我的分區功能有問題。 它在Java中,並且是所有與數組排序有關的類的一部分。
分區的工作方式如下:數組中有兩個索引i和j,在分區算法的最開始,i指向數組中的第一個元素,j指向最后一個元素。 然后,算法將i向前移動,直到找到一個值大於或等於樞軸的元素。 索引j向后移動,直到找到一個值小於或等於樞軸的元素。 如果i≤j,則將它們交換,並且i移至下一個位置(i + 1),j移至上一個位置(j-1)。 當i大於j時,算法停止。
您能看到問題出在哪里嗎,因為我找不到它。 幫助將不勝感激。
public static int partition(int arr[], int left, int right)
{
int x = arr[right];
int i = left-1;
int temp=0;
for (int j=left; j<right; j++)
{
if(arr[j]<=x)
{
i++;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
temp = arr[i+1];
arr[i+1] = arr[right];
arr[right] = temp;
return (i+1);
}
編輯
Eclipse表示存在兩個問題,一個是分區函數中的這一行代碼:
int x = arr[right];
在我的測試課的這一行:
sort.partition(array, 100, array.length);
這是測試類,其中包括我未提及的功能。
import java.util.Random;
public class test {
/**
* @param args
*/
public static void main(String[] args) {
int size = 1000;
int max = 5000;
int[] array = new int[size];
int loop = 0;
Random generator = new Random();
//Write a loop that generates 1000 integers and
//store them in the array using generator.nextInt(max)
generator.nextInt(max); //generating one
//I need to generate 1000
//So I need some kind of loop that will generate 1000 numbers.
for (int i =0; i<1000; i++)
{
generator.nextInt(max);
}
/**
* After I do this, I'll have the array, array.
* Then comes what's under this.
* THat method is for measuring the time.
* System.currentTimeMillis();,
* with this, I can collect a time for the start of the method
* and one for the end.
* Time at the end, minus the time at the start
* gets us the running time.
*/
long result;
long startTime = System.currentTimeMillis();
sort.quickSort(array, 100, array.length-1);
long endTime = System.currentTimeMillis();
result = endTime-startTime;
System.out.println("The quick sort runtime is " + result + " miliseconds");
long result2;
long startTime2 = System.currentTimeMillis();
sort.partition(array, 100, array.length);
long endTime2 = System.currentTimeMillis();
result2 = endTime2 - startTime2;
System.out.println("The partition runtime is "+result2 + " miliseconds");
long result3;
long startTime3 = System.currentTimeMillis();
sort.bubbleSort(array, 100);
long endTime3 = System.currentTimeMillis();
result3 = endTime3-startTime3;
System.out.println("The bubble sort runtime is "+result3 + " miliseconds");
long result4;
long startTime4 = System.currentTimeMillis();
sort.selectionSort(array, 100); //change the second number to change
//the size of an array.
long endTime4 = System.currentTimeMillis();
result4 = endTime4-startTime4;
System.out.println("The selection sort runtime is "+result4 + " miliseconds");
}
}
首先,您實際上並未將隨機數存儲在數組中,因此它將全部為零。
至於您所看到的實際錯誤,您只有一個錯誤而已。 您有兩種選擇: right
指向數組的末尾,或者指向數組的末尾。 任一種有效,但您要混合兩種。
具體來說,您要傳遞1000(即數組末尾的第一個)以獲取right
值,但隨后您立即使用該數組對索引進行索引,自然會引發異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.