a348725767 2011-09-19 22:08
浏览 189
已采纳

java数据结构

看到排序 有点看不懂希尔排序,划分,快速排序,求解释

  • 写回答

1条回答 默认 最新

  • turing-complete 2011-09-20 09:31
    关注

    [code="java"]package sorts;

    import java.util.Stack;

    //对int数组进行快排的类
    public class QuickSort {

    private int[] data;// 待排序数组
    
    public QuickSort(int[] para) {
        this.data = para;
    }
    
    // 划分方法,类内使用
    private int partition(int i, int j) {
        int pivot = this.data[i];// 关键值
        while (true) {
            for (; this.data[j] >= pivot && i < j; --j);
            if (i == j) {
                break;
            }
            this.data[i] = this.data[j];
            for (; this.data[i] <= pivot && i < j; ++i);
            if (i == j) {
                break;
            }
            this.data[j] = this.data[i];
        }
        this.data[i] = pivot;// 还原关键值的位置
        return i;
    }
    
    // 递归快排
    private void recur(int low, int high) {
        int pivotpos; // 划分后的基准记录的位置
        if (low < high) {// 仅当区间长度至少为2时才排序
            pivotpos = this.partition(low, high); // 对R[low..high]做划分
            this.recur(low, pivotpos - 1); // 对左区间递归排序
            this.recur(pivotpos + 1, high); // 对右区间递归排序
        }
    }
    
    // 递归快排结果
    public void sort_recur() {
        this.recur(0, this.data.length - 1);
    }
    
    // 非递归快排
    public void sort() {
        Stack<Integer> stack = new Stack<Integer>();
        int start = 0;
        int end = this.data.length - 1;
        int pivot;
        while (true) {
            if (end > start) {
                pivot = this.partition(start, end);
                if (end > pivot + 1) {// 后一段入栈
                    stack.push(end);
                    stack.push(pivot + 1);
                }
                end = pivot - 1;
                if (stack.empty()) {
                    break;// 退出函数
                }
            } else {// 结果出栈
                start = stack.pop();
                end = stack.pop();
            }
        }
    }
    
    // 测试代码
    public static void main(String[] args) {
        int a[] = new int[] { 9, 8, 23, 1, 6, 5, 11, 43, 4, 13 };
        // new QuickSort(a).partition(0, a.length-1);
        // new QuickSort(a).sort_recur();
        new QuickSort(a).sort();
        for (int i : a) {
            System.out.println(i);
        }
    }
    

    }
    [/code]

    带注释的毕竟好懂些

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 MPLAB IDE V2.35 报错make[2]: *** [build/default/production/_ext/1472/MSSP_I2C.p1] Error 1
  • ¥15 新唐M451 DTMF检测和发送代码修改
  • ¥15 在国外文献网站里点击view pdf 加载异常缓慢甚至加载不出来。
  • ¥65 python批量提取发票的信息
  • ¥15 虚幻五引擎内容如何上传至网盘?
  • ¥15 使用mmpose库时出现了问题
  • ¥15 IRI2016模型matlab运行报错
  • ¥50 bat怎么设置电脑后台自动点击网页指定词运行脚本,输入指定网页链接,指定点击词,指定间隔时间,指定网页出现的词,指定网页出现词出现后后点击锁定,放在后台运行不影响前台鼠标工作
  • ¥20 20CrMnMo的高温变形抗力
  • ¥15 RTX3.6 5565驱动中断报错