快排、归并非递归

归并、快排非递归

归并非递归

非递归归并排序将每一个元素都看作是有序的,然后将这些有序的元素递归

  public static void anotherMergeSort(int[] array) {
        for(int i = 1;i < array.length;i *= 2) {
            merge(array,i);
        }
        System.out.println(Arrays.toString(array));
    }
    public static void merge(int[] array,int step) {
        int len = array.length;
        int s1 = 0;
        int e1 = s1 + step - 1;
        int s2 = e1 + 1;
        int e2 = s2 + step - 1 < len ? s2 + step - 1 : len - 1;
        int[] temp = new int[len];
        int k = 0;
        while(s2 < len) {
            while(s1 <= e1 && s2 <= e2) {
                if(array[s1] <= array[s2]) {
                    temp[k++] = array[s1++];
                }else {
                    temp[k++] = array[s2++];
                }
            }

            while(s1 <= e1) {
                temp[k++] = array[s1++];
            }

            while(s2 <= e2) {
                temp[k++] = array[s2++];
            }

            s1 = s2 + 1;
            e1 = s1 + step - 1;
            s2 = s1 + 1;
            e2 = s2 + step - 1 < len ? s2 + step - 1 : len - 1;
        }

        while(s1 < len - 1) {
            temp[k++] = array[s1++];
        }
            array = Arrays.copyOf(temp,temp.length);
    }

快排非递归

快排非递归的实现主要依赖于栈,用栈存储每次划分的范围,然后对每个范围内再进行基准划分。

public static void anotherQuickSort (int[] array) {
    Stack<Integer> stack = new Stack();
    int left = 0;  
    int right = array.length - 1;
    stack.push(right);
    stack.push(left);
    while(!stack.isEmpty()) {
        //栈先入后出,先出栈的是start
        //出栈和入栈顺序要搞清楚
        int start = stack.pop();
        int end = stack.pop();
        int pov = partition(array,start,end);
        //找到基准后,按照基准划分
        stack.push(end);
        stack.push(pov + 1);
        stack.push(pov - 1);
        stack.push(start);
    }
}

public static int partition(int[] array,int start,int end) {
    int temp = array[start];
    while(start < end) {
        while(start < end && array[end] >= temp) {end--;}
        array[start] = array[end];
        while(start < end && array[start] <= temp) {start++;}
        array[end] = array[start];
    }
    array[start] = temp;
    return start;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值