通用多线程快速排序java

时间:2017-05-20 11:54:27

标签: java multithreading quicksort

我已经获得了以这种方式修改quicksort程序的任务,因此它使用泛型及其多线程。我对代码的问题是,与非线程调用相比,Multi thread Integer quicksort调用需要更长的时间才能完成。

这是我的两种实现 - 非线程和多线程,我在找到我所犯的错误时遇到了问题。

class GenericQuicksort {

private static void swap(Comparable[] array, int i, int j) {
    Comparable temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}

public static Comparable[] quickSort(Comparable[] array) {
    return qs(array, 0, array.length - 1);
}

private static Comparable[] qs(Comparable[] array, int left, int righ) {
    int i = left;
    int j = righ;
    Comparable pivot = array[(left + righ) / 2];
    do {
        while ((array[i].compareTo(pivot) == -1) && (i < righ)) i++;
        while ((pivot.compareTo(array[j]) == -1) && (j > left)) j--;
        if (i <= j) {
            swap(array, i++, j--);
        }
    } while (i <= j);
    if (left < j) qs(array, left, j);
    if (i < righ) qs(array, i, righ);
    return array;
}

public static Comparable[] quickSortMulti(Comparable[] array) {
    GsMultiThread gsMultiThread = new GsMultiThread(array, 0, array.length - 1, 0);
    gsMultiThread.start(); //Not needed to start a new thread.
    try {
        gsMultiThread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return array;
}

static class GsMultiThread extends Thread {

    Comparable[] array;
    int left;
    int right;
    int ii;

    public GsMultiThread(Comparable[] array, int left, int right, int i) {
        this.array = array;
        this.left = left;
        this.right = right;
        this.ii = ++i;
    }

    @Override
    public void run() {
        int i = left;
        int j = right;
        Comparable pivot = array[(left + right) / 2];
        do {
            while ((array[i].compareTo(pivot) == -1) && (i < right)) i++;
            while ((pivot.compareTo(array[j]) == -1) && (j > left)) j--;
            if (i <= j) {
                swap(array, i++, j--);
            }
        } while (i <= j);
        GsMultiThread threada = null;
        GsMultiThread threadb = null;
        if (left < j) {
            if (i > 2) {
                qs(array, left, j);
            } else {
                threada = new GsMultiThread(array, left, j, ii);
                threada.start();
            }
        }
        if (i < right) {
            if (i > 2) {
                qs(array, i, right);
            } else {
                threadb = new GsMultiThread(array, i, right, ii);
                threadb.run();
            }
        }
        try {
            if (threada != null)
                threada.join();
            if (threadb != null)
                threadb.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

}

0 个答案:

没有答案