十种排序算法及其比较(java实现)

十种排序算法及其比较(java实现)_第1张图片
图1 十大排序算法(参考自[[K_天道酬勤的CSDN博客](http://blog.csdn.net/qq_21688757/article/details/53749198)])

快速排序

public static int[] QuickSort(int[] array) {
    int[] value = new int[array.length];
    System.arraycopy(array, 0, value, 0, array.length);
    QuickSortRecursive(value, 0, value.length - 1);
    return value;
}

private static void QuickSortRecursive(int[] value, int start, int end) {
    if (start >= end)
        return;
    int mid = value[end];
    int left = start, right = end - 1;
    while (left < right) {
        while (value[left] <= mid && left < right)
            left++;
        while (value[right] >= mid && left < right)
            right--;
        swap(value, left, right);
    }
    if (value[left] >= mid)
        swap(value, left, end);
    else
        left++;
    QuickSortRecursive(value, start, left - 1);
    QuickSortRecursive(value, left + 1, end);
}

Q1:为什么是从右边开始,寻找第一个比枢纽小的数,而不是从左边开始,寻找第一个比枢纽大的数?
如果从左边开始,寻找第一个比枢纽大的数,无法进行枢纽判断。

归并排序

public static int[] MergeSort(int[] arr) {
    int len = arr.length;
    int[] value = new int[len], temp = new int[len];
    System.arraycopy(arr, 0, value, 0, len);
    MergeSortRecursive(value, temp, 0, len - 1);
    return value;
}

private static void MergeSortRecursive(int[] value, int[] temp, int start, int end) {
    if (start >= end)
        return;
    int len = end - start, mid = start + (len >> 1);
    int start1 = start, end1 = mid;
    int start2 = mid + 1, end2 = end;
    MergeSortRecursive(value, temp, start1, end1);
    MergeSortRecursive(value, temp, start2, end2);
    int k = start;
    while (start1 <= end1 && start2 <= end2)
        temp[k++] = value[start1] <= value[start2] ? value[start1++] : value[start2++];
    while (start1 <= end1)
        temp[k++] = value[start1++];
    while (start2 <= end2)
        temp[k++] = value[start2++];
    for (k = start; k <= end; k++)
        value[k] = temp[k];
}

堆排序

private static int[] HeapSort(int[] arr) {
    int length = arr.length;
    int[] value = new int[length];
    System.arraycopy(arr, 0, value, 0, length);
    int len = length - 1, beginIndex = len >> 1, k;
    for (k = beginIndex; k >= 0; k--)
        HeapMax(value, k, len);
    for (k = len; k > 0; k--) {
        swap(value, k, 0);
        HeapMax(value, 0, k - 1);
    }
    return value;
}

private static void HeapMax(int[] value, int index, int len) {
    int lIndex = (index << 1) + 1, rIndex = lIndex + 1, mIndex = lIndex;
    if (lIndex > len)
        return;
    if (rIndex <= len && value[lIndex] < value[rIndex])
        mIndex = rIndex;
    if (value[mIndex] > value[index]) {
        swap(value, mIndex, index);
        HeapMax(value, mIndex, len);
    }
}

你可能感兴趣的:(十种排序算法及其比较(java实现))