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.
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