I am trying to write a quick sort
for Strings
. I wrote the code and it works when I run the program. I am able to successfully sort the array. When applying quick sort, you separate the array from 0 - (x - 1)
and (x + 1) - y
, where x is the pivot position and y is the end of the array. I want to be able to choose my own pivot in my main method rather than continually using the last entry of the array as a pivot.
Problem is, I can't think of a way to apply this. I have tried editing the call to quick sort to be quicksort(blah, 0, pivot_position)
and edit my quicksort method to quicksort(list, q + 1, list.length - 1)
. It runs, but it's not sorted. Can I receive any help in figuring this out? Thank you.
*Also, this is all ran through a Terminal.
public static void quicksort(String[] list, int p, int r)
{
if(p < r)
{
int q = partition(list, p, r);
quicksort(list, p, q - 1);
quicksort(list, q + 1, r); //quicksort(list, q + 1, list.length - 1)
}
}
public static int partition(String[] list, int p, int r)
{
String x = list[r];
int i = p - 1;
for(int j = p; j <= r - 1; j++)
{
if(list[j].compareTo(x) <= 0)
{
i++;
swap(list, i, j);
}
}
swap(list, i + 1, r);
return i + 1;
}
public static void main(String[] args)
{
int pivot_position = Integer.parseInt(args[1]);
String[] blah = [a, zy, o, z, je];
quicksort(blah, 0, blah.length - 1); // quicksort(blah, 0, pivot_position)
for(String i : blah)
{
System.out.println(i);
}
}