0

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);
    }
}
user3339453
  • 57
  • 1
  • 7
  • I did not include my swap method. It takes up unnecessary space towards the objective of the question. – user3339453 Mar 12 '14 at 04:12
  • The wikipedia article on [quicksort](http://en.wikipedia.org/wiki/Quicksort#Choice_of_pivot) goes pretty in depth on the pitfalls of pivot selection. – aruisdante Mar 12 '14 at 04:15
  • Yes, I know it'll cause the worst behavior of quick sort. But I just want to figure out if I could write the code. – user3339453 Mar 12 '14 at 04:18
  • Continue going down, it talks about other selection methods that are more dynamic in nature. – aruisdante Mar 12 '14 at 04:24

0 Answers0