数据结构:带有Java的quicksortlinkedList

时间:2018-11-16 12:37:04

标签: java data-structures quicksort

当使用LinkedList而不是数组时,是否有办法获得相同的结果?仅当Im以其泛型形式使用数组时,以下代码才能完美运行。我想通过使用LinkedList来做同样的事情。像这样:

public static <E extends Comparable<E>> LinkedList<E> qSort(LinkedList<E> list) {

    return list;
}

这是我已经拥有的。

 public static <E extends Comparable<E>> E[] quickSort(E[] list) {
    if (list.length <= 1) {
        return list;
    }
    sort(list, 0, list.length - 1);
    return list;
}

public static <E extends Comparable<E>> void sort(E[] list, int low, int high) {

    if ((high - low) <= 0) {
        return;
    }
    int splitPoint = split(list, low, high);
    sort(list, low, splitPoint - 1);
    sort(list, splitPoint + 1, high);
}

private static <E extends Comparable<E>> int split(E[] list, int low, int high) {
    int left = low + 1;
    int right = high;
    E pivot = list[low];
    while (left <= right) {
        if (list[left].compareTo(pivot) < 0) {
            left++;
        } else {
            break;
        }
    }
    while (true) {

        while (right > left) {
            if (list[right].compareTo(pivot) < 0) {
                break;
            } else {
                right--;
            }
        }

        if (left >= right) {
            break;
        }

        E temp = list[left];
        list[left] = list[right];
        list[right] = temp;
        left++;
        right--;
    }

    list[low] = list[left -1];
    list[left-1] = pivot;

    return left-1;
}

0 个答案:

没有答案