栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JAVA快速排序栈实现(非递归)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JAVA快速排序栈实现(非递归)

快速排序非递归方法,使用栈实现的,入栈和出栈相当于递归操作

public static void quickSort(int[] arr, int startIndex, int endIndex) {
        // 用一个集合栈来代替递归的函数栈
        Stack> quickSortStack = new Stack>();
        // 整个数列的起止下标,以哈希的形式入栈
        Map rootParam = new HashMap();
        rootParam.put("startIndex", startIndex);//将头节点和下标放进去
        rootParam.put("endIndex", endIndex);
        quickSortStack.push(rootParam);//入栈

        // 循环结束条件:栈为空时结束
        while (!quickSortStack.isEmpty()) {
            // 栈顶元素出栈,得到起止下标
            Map param = quickSortStack.pop();
            // 得到基准元素位置
            int pivotIndex = partition(arr, param.get("startIndex"), param.get("endIndex"));
            // 根据基准元素分成两部分, 把每一部分的起止下标入栈
            if(param.get("startIndex") <  pivotIndex -1){
                Map leftParam = new HashMap();
                //记录起止的坐标
                leftParam.put("startIndex",  param.get("startIndex"));
                leftParam.put("endIndex", pivotIndex -1);
                quickSortStack.push(leftParam);//入栈
            }
            if(pivotIndex + 1 < param.get("endIndex")){
                Map rightParam = new HashMap();
                rightParam.put("startIndex", pivotIndex + 1);
                rightParam.put("endIndex", param.get("endIndex"));
                quickSortStack.push(rightParam);
            }
        }
    }

 排序还是一样的

 private static int partition(int[] arr, int startIndex, int endIndex) {
        // 取第一个位置的元素作为基准元素(也可以选择随机位置)
        int pivot = arr[startIndex];
        int mark = startIndex;

        for(int i=startIndex+1; i<=endIndex; i++){
            if(arr[i] 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/937325.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号