I am trying to implement a Randomized Select Algorithm Quick Sort. I have pretty much implemented the rest of the pseudo-code except for one line.
The pseudo-code for the randomized select algorithm is this: http://ift.tt/1MCMzj5
My main issue is the partition method.
RANDOMIZED-PARTITION(A, p, r)
i = RANDOM(p, r)
exchange A[r] ↔ A[i]
return PARTITION(A, p, r)
I have tried implementing it like this:
Random rand = new Random();
int i = rand.nextInt(r - p) + p + 1;
swap(array, r, i);
return partition(array, p, r);
I know that RANDOM is a method in the pseudo-code, and I know that I shouldn't add 1 at the end of i, but if I don't, it gives me the error of "bounds must be positive". This is only for testing purposes. I know that at some point r reaches -1.
Example Output:
Please enter a small n: 10
The unsorted array is:
51 5 10 70 57 72 98 93 69 51
Randomized Select:
5 10 51 51 57 69 98 93 70 72
It sorts half of the array, but not the other half, and I think the main issue is i since it's used for swapping.
My question is, how do I implement i = RANDOM(p, r)? How would I go about implementing my own RANDOM method for this case?
I can post the whole code if this is not enough info.
Aucun commentaire:
Enregistrer un commentaire