tags:

views:

96

answers:

2
private static char[] quicksort (char[] array , int left , int right) {
    if (left < right) {
        int p = partition(array , left, right);
        quicksort(array, left, p − 1 );
        quicksort(array, p + 1 , right);
    }
    for (char i : array)
    System.out.print(i + ” ”);
    System.out.println();
    return array;
}
private static int partition(char[] a, int left, int right) {
    char p = a[left];
    int l = left + 1, r = right;
    while (l < r) {
        while (l < right && a[l] < p) l++;
        while (r > left && a[r] >= p) r−−;
        if (l < r) {
            char temp = a[l];
            a[l] = a[r];
            a[r] = temp;
        }
    }
    a[left] = a[r];
    a[r] = p;
    return r;
    }
}

I have a question regarding the above coding, I know that the above coding returns the following

B I G C O M P U T E R
B C E G I M P U T O R
B C E G I M P U T O R
B C E G I M P U T O R
B C E G I M P U T O R
B C E G I M O P T U R
B C E G I M O P R T U
B C E G I M O P R T U
B C E G I M O P R T U
B C E G I M O P R T U
B C E G I M O P R T U
B C E G I M O P R T U
B C E G I M O P R T U

when the sequence BIGCOMPUTER is used, but my question is can someone explain to me what is happening in the code and how?

I know a bit about the quick-sort algorithm but it doesn't seem to be the same in the above example.

+2  A: 

That is quicksort. If you understand the algorithm, you'll recognize it even when implemented differently. This one in particular is actually the standard way you'd implement it in imperative languages.

References

polygenelubricants
+1  A: 

This is a typical use case for a debugger. Run the code through your debugger and step through it, examining the call stack and local variables as you go. Should be pretty clear what's happening.

If you aren't familiar with debuggers it's never too early to start imho, here are some excellent video tutorials for Eclipse.

JRL
+1; but I don't think a debugger can help someone understand quicksort without at least some high level grasp of the algorithm. In many of these beginners question, though, a healthy dose of step-through debugging is what they need.
polygenelubricants
@polygenelubricants: the OP states he knows about quicksort, so i believe what's left is understanding what each line in the code does, for which I believe a debugger is a great asset. Especially for recursive calls, being able to "see" the call stack helps reduce the complexity of recursion.
JRL