[算法入门]快速排序非递归方法(Java实现),大家一起来找茬啊~

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/haolvshiqi/article/details/54290670

基础

总结一下,快速排序的步骤:
1、找到一个key值(就是数组第一个值),先从右到左找,找到一个比它小的值,记录下标。
2、然后从左往右找,找到一个比它大的值,记录下标。
3、交换找到的两个数字。
4、继续,直到从右往左找的数字和从左往右找的数字下标重合。交换key值和重合值。
5、这时key值左边就全是比它小的数字,key值右边全是比它大的数字。
6、以key值为基准,将数组分为两段,左边和右边重新进行以上5步。

所以在程序中每次循环我们需要记录的值有:
1、从右往左找时,比key值大的下标
2、从左往右找时,比key值小的下标
3、key值
4、将数组分段后,每段的最小下标和最大下标。

对于第4点,因为java中有现在堆栈这种数据结构,好了,不选了,就用它来存储。下面直接贴上源代码。

public int[] quickSort_not_recursion(int[] result) {
        int i;
        int j;
        int min;    // Every loop's max index
        int max;    // Every loop's minus index
        int key;

        Stack<Integer> conditions = new Stack<Integer>();   // Record the minus index and the max index
        conditions.push(0);
        conditions.push(result.length-1);
        int temp;

        // In every loop will get a left index and right index.
        while(!conditions.empty()){
            max = conditions.pop();
            min = conditions.pop();
            key = result[min];
            i = min+1;
            j = max;

            // With this step, the numbers can be divided to 2 sections,
            // the left side is smaller than the key value,
            // the right side is bigger than the key value.
            while(i<j) {
                // Get the number's index which is smaller than key
                while (key < result[j] && i<j) {
                    j--;
                }

                // Get the number's index which is bigger than key
                while (key > result[i] && i<j) {
                    i++;
                }

                // Swap
                temp = result[j];
                result[j] = result[i];
                result[i] = temp;
            }

            // Swap the key and i(or j)
            if(key>result[i]){
                temp = result[min];
                result[min] = result[j];
                result[j] = temp;
            }

            // Store the left side minus index and the max index
            if(min<i-1){
                conditions.push(min);
                conditions.push(i-1);
            }

            // Store the right side minus index and the max index
            if(max>i+1){
                conditions.push(i+1);
                conditions.push(max);
            }
        }

        return result;
    }

猜你喜欢

转载自blog.csdn.net/haolvshiqi/article/details/54290670
今日推荐