I have the following class for Quicksorting.
import java.util.Random;
public class QuickSorter {
public static void main(String[] args) {
Random random = new Random();
int[] randoms = new int[10000];
for(int i = 0; i < randoms.length; i++) randoms[i] = random.nextInt(10000);
quickSort(randoms, 0, randoms.length);
System.out.println(Arrays.toString(randoms));
}
/** Same as {@link #quickSort(int[], int, int)}, but assumes the whole array should be sorted. */
public static void quickSort(int[] in) {quickSort(in, 0, in.length);}
/** Sorts an array of integers using the Quicksort algorithm, in the range [{@code start}, {@code end}).
* @param in The full array to sort
* @param start The starting index, inclusive
* @param end The ending index, exclusive
* @see #quickSort(int[]) */
public static void quickSort(int[] in, int start, int end) {
int pivot = (start + end) / 2;
/* Temporary array containing the ordered sub-list */
int[] sub = new int[end - start];
int left = 0, right = sub.length;
/* Populate the sub-list */
for(int i = start; i < end; i++) {
if(i == pivot) continue;
if(in[i] < in[pivot]) {
sub[left++] = in[i];
} else {
sub[--right] = in[i];
}
}
/* Add in the original pivot in its new position */
sub[left] = in[pivot];
/* Copy back into the original array */
for(int k = start; k < end; k++) {
in[k] = sub[k - start];
}
/* Translate new pivot position into full list index */
left += start;
if(left - start > 0) quickSort(in, start, left);
/* The start of the right branch should not include the pivot */
left++;
if(end - left > 0) quickSort(in, left, end);
}
}
Is this the most efficient way to Quicksort? I feel as if copying the values from sub
back into in
can be done better somehow.
And of course, I know this won't cause any huge issues with arrays of size 10000
. But, I'd like this to hold up all the way up to 2^31-1
(to the limits of max array size).
n
allocations for a half ofn
–squared items in the worst case (orlog(n)
allocations for2n
items in the best case) is certainly NOT a quick way to sort the array... \$\endgroup\$