排序算法

//冒泡排序
public static int[] MaoPaoSort(int[] a) {
    for (int i = 0; i < a.length; ++i) {
        for (int j = 0; j < a.length - i - 1; ++j) {
            if (a[j] > a[j + 1]) {
                int temp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = temp;
            }
        }
    }

    return a;
}

//选择排序
public static int[] SelectSort(int[] a) {
    for (int i = 0; i < a.length; ++i) {
        for (int j = i + 1; j < a.length; ++j) {
            if (a[i] > a[j]) {
                int temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
    }

    return a;
}

//插入排序
public static int[] InsertSort(int[] a) {
    for (int i = 1; i < a.length; ++i) {
        for (int j = i; j > 0; --j) {
            if (a[j - 1] > a[j]) {
                int temp = a[j - 1];
                a[j - 1] = a[j];
                a[j] = temp;
            }
        }
    }

    return a;
}

//希尔排序
public static int[] XiErSort(int[] a) {
    for (int d = a.length / 2; d > 0; d /= 2) {
        for (int i = d; i < a.length; ++i) {
            for (int j = i - d; j >= 0; j -= d) {
                if (a[j] > a[j + d]) {
                    int temp = a[j];
                    a[j] = a[j + d];
                    a[j + d] = temp;
                }
            }
        }
    }

    return a;
}

//快速排序
public static int[] QuiteSort(int[] a, int begin, int end) {
    if (end - begin <= 1) {
        return null;
    }
    int x = a[begin];
    int p1 = begin;
    int p2 = end;
    boolean dr = true;

    L1:
    while (p1 < p2) {
        if (dr) {
            for (int i = p2; i > p1; i--) {
                if (a[i] < x) {
                    a[p1++] = a[i];
                    p2 = i;
                    dr = !dr;
                    continue L1;
                }
            }
            p2 = p1;
        } else {
            for (int i = p1; i < p2; i++) {
                if (a[i] >= x) {
                    a[p2--] = a[i];
                    p1 = i;
                    dr = !dr;
                    continue L1;
                }
            }
            p1 = p2;
        }
    }
    a[p1] = x;//标尺放入
    QuiteSort(a, begin, p1 - 1);
    QuiteSort(a, p1 + 1, end);
    return a;
}

你可能感兴趣的:(排序算法)