Monday 15 March 2010

java - Array out of bounds error with quick sorting -



java - Array out of bounds error with quick sorting -

i'm not sure why, keeps giving me array out of bounds error when compile it. assuming array initialized correctly have 10 index positions , pass method 0 , numbers.length - 1, doing wrong?

public void sort(int low, int high) { int temp1 = low; int temp2 = high; int pivot = numbers[low + (high - low)/2]; while(temp1 <= temp2) { while(numbers[temp1] < pivot) { temp1++; } while(numbers[temp2] > pivot) { temp2--; } if(temp1 <= temp2) { swap(temp1, temp2); temp1++; temp2--; } } if(low < temp1) { sort(low, temp2); } if(temp2 < high) { sort(temp2, high); } } public void swap(int temp1, int temp2) { int temp = numbers[temp1]; numbers[temp1] = numbers[temp2]; numbers[temp2] = temp; }

this:

if(low < temp1) { sort(low, temp2); }

should be

if(low < temp2) { sort(low, temp2); }

and this:

if(temp2 < high) { sort(temp2, high); }

should be:

if(temp1 < high) { sort(temp1, high); }

this doesn't explain error seeing, sorting much of sub-arrays. don't need include pivot value in recursive sort; it's in right place.

also:

while(temp1 <= temp2)

could be:

while(temp1 < temp2)

... since there's no point trying swap element itself. leave loop temp1 == temp2, in case might want adjust later recursive calls; perhaps leaving status temp1 <= temp2 improve bet.

java arrays quicksort

No comments:

Post a Comment