H
hiwa
If there are duplicate values in the data set, James Gosling's
QSortAlgorithm does freeze. What should be the cause and what
could be the solution?
Here's a test program:
public class GoslingQsort{
public static void main(String[] args){
int[] data1 = {68, 0, 54, 26, 6, 54, 57, 35, 9, 45}; //freezes
int[] data2 = {68, 0, 54, 26, 6, 14, 57, 35, 9, 45}; //normal
int[] data = args.length > 0 ? data2 : data1; //you can
//compare
printArray("initial", data);
QSortAlgorithm qsa = new QSortAlgorithm();
qsa.sort(data);
printArray("result ", data);
}
static void printArray(String s, int[] a){
System.out.print(s + ": ");
for (int i = 0; i < a.length; ++i){
System.out.print(a + " ");
}
System.out.println();
}
}
/**
* A quick sort demonstration algorithm
* @author James Gosling
* @history Modified by Pat Morin, 7 Feb 1996
*/
class QSortAlgorithm {
/*Uses quick sort to sort the array between the specified
indices*/
void sort(int a[], int lo0, int hi0){
int lo = lo0;
int hi = hi0;
if (lo >= hi) {
return;
}
int mid = a[(lo + hi) / 2];
while (lo < hi) {
while (lo<hi && a[lo] < mid) {
lo++;
}
while (lo<hi && a[hi] > mid) {
hi--;
}
if (lo < hi) {
int T = a[lo];
a[lo] = a[hi];
a[hi] = T;
}
}
if (hi < lo) {
int T = hi;
hi = lo;
lo = T;
}
sort(a, lo0, lo);
sort(a, lo == lo0 ? lo+1 : lo, hi0);
}
/*Sorts the given array using the quicksort algorithm.*/
void sort(int a[]){
sort(a, 0, a.length-1);
}
}
QSortAlgorithm does freeze. What should be the cause and what
could be the solution?
Here's a test program:
public class GoslingQsort{
public static void main(String[] args){
int[] data1 = {68, 0, 54, 26, 6, 54, 57, 35, 9, 45}; //freezes
int[] data2 = {68, 0, 54, 26, 6, 14, 57, 35, 9, 45}; //normal
int[] data = args.length > 0 ? data2 : data1; //you can
//compare
printArray("initial", data);
QSortAlgorithm qsa = new QSortAlgorithm();
qsa.sort(data);
printArray("result ", data);
}
static void printArray(String s, int[] a){
System.out.print(s + ": ");
for (int i = 0; i < a.length; ++i){
System.out.print(a + " ");
}
System.out.println();
}
}
/**
* A quick sort demonstration algorithm
* @author James Gosling
* @history Modified by Pat Morin, 7 Feb 1996
*/
class QSortAlgorithm {
/*Uses quick sort to sort the array between the specified
indices*/
void sort(int a[], int lo0, int hi0){
int lo = lo0;
int hi = hi0;
if (lo >= hi) {
return;
}
int mid = a[(lo + hi) / 2];
while (lo < hi) {
while (lo<hi && a[lo] < mid) {
lo++;
}
while (lo<hi && a[hi] > mid) {
hi--;
}
if (lo < hi) {
int T = a[lo];
a[lo] = a[hi];
a[hi] = T;
}
}
if (hi < lo) {
int T = hi;
hi = lo;
lo = T;
}
sort(a, lo0, lo);
sort(a, lo == lo0 ? lo+1 : lo, hi0);
}
/*Sorts the given array using the quicksort algorithm.*/
void sort(int a[]){
sort(a, 0, a.length-1);
}
}