简单快速理解算法--快速排序

我自己实现的有点bug,就是数组元素不能拥有重复,不知道咋修改。

package cn.exercise.algorithmsTest;

public class QuickSort2 {

    public static void qsort_asc(int source[], int low, int high) {
        int temp1[] = new int[source.length];
        int temp2[] = new int[source.length];
        int i, j, key;
        if (low < high) {
            i = low;
            j = high;
            key = source[i];
            while (i < j && i != j) {

                while (i < j && source[j] > key) {
                    j--;
                }
                if (i < j) {
                    temp1[i] = source[i];
                    source[i] = source[j];
                    source[j] = temp1[i];
                }

                while (i < j && source[i] < key) {
                    i++;
                }
                if (i < j) {
                    temp2[j] = source[j];
                    source[j] = source[i];
                    source[i] = temp2[j];
                }
            }

            source[i] = key;
            qsort_asc(source, low, i - 1);
            qsort_asc(source, i + 1, high);
        }
    }

    public static void main(String[] args) {
        int b[] = { 49, 38, 65, 97, 76, 13, 27, 50 };
        qsort_asc(b, 0, b.length - 1);

        for (int i = 0; i < b.length; i++) {
            System.out.printf("%d ", b[i]);
        }
    }

}
  • 设置两个变量i,j,排序开始的时候,i = 0;j = N-1
  • 以第一组数组元素作为关键数据,赋值给key,即key = source[0]
  • 从j开始向前搜索,即逆向遍历数组,找到第一个小于key的值sorce[j],将source[j]和source[i]互换
  • 从i开始向前搜索,即正向遍历数组,找到第一个大于key的值sorce[i],将source[i]和source[j]互换
  • 重复上两步,直到i=j。至此,完成了一趟遍历。
  • 接着让key赋值给sorce[i],然后重复掉用查询方法对低位到i-1,和i+1到高位。之后便可以完成排序。

官方的快速排序如下

package cn.exercise.algorithmsTest;

public class QuickSort {

    public static void qsort_asc(int source[], int low, int high) {
        int i, j, key;
        if (low < high) {
            i = low;
            j = high;
            key = source[i];
            while (i < j) {

                while (i < j && source[j] > key) {
                    j--;
                }
                if (i < j) {
                    source[i] = source[j];
                    i++;
                }

                while (i < j && source[i] < key) {
                    i++;
                }
                if (i < j) {
                    source[j] = source[i];
                    j--;
                }
            }

            source[i] = key;
            qsort_asc(source, low, i - 1);
            qsort_asc(source, i + 1, high);
        }

    }

    public static void main(String[] args) {
        int[] a = { 5, 2, 6, 3, 8 };
        int i;
        qsort_asc(a, 0, a.length-1);

        for (i = 0; i < a.length; i++) {
            System.out.printf("%d ",a[i]);
        }
    }

}

你可能感兴趣的:(算法的学习)