堆排序 快排

堆排序关系
parent = (i-1) / 2
left = 2i + 1
right = 2i+2

public class HeapSort {

    public static void main(String []args){
        int tree [] = {10,3,4,9,11};
        int n = 5;
        heapSort(tree,n);
        for (int i : tree){
            System.out.println(i);
        }
    }

    static void heapSort(int tree[],int n){
        buildHeap(tree,n);
        int i ;
        //首尾交换
        for (i = n - 1; i >= 0; i--){
            swap(tree,i,0);
            heapify(tree,i,0);
        }
    }

    static void buildHeap(int tree[],int n){
        int lastNode = n-1;
        int parent = (lastNode - 1) / 2 ;//父节点
        int i ;
        for (i = parent; i >= 0 ; i--){
            heapify(tree,n,i);
        }
    }
   static void heapify(int tree[], int n, int i) {

        if (i >= n) return;
        int left = 2 * i + 1; //左树位置
        int right = 2 * i + 2; //右树位置
        int max = i;
        if (left < n && tree[left] > tree[max]) {
            max = left;
        }
        if (right < n && tree[right] > tree[max]) {
            max = right;
        }
        if (max != i) {
            swap(tree, max, i);
            heapify(tree, n, max);
        }
    }

    static void swap(int arr[], int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}

package com;

import com.alibaba.fastjson.JSONObject;

public class QuickSort {

    static void partition(int a[], int low, int high) {
        if (low >= high) return;
        int pivot = a[low], i = low, j = high;
        while (i < j) {
            while (i < j && a[j] > pivot) --j;
            if (i < j) a[i++] = a[j];
            while (i < j && a[i] <= pivot) ++i;
            if (i < j) a[j--] = a[i];
        }
        a[i] = pivot;
        partition(a, low, i - 1);
        partition(a, i + 1, high);
    }


    public static void main(String[] args) {
        int[] data = {2, 3, 1, 7, 5};
        partition(data, 0, 4);
        System.out.println(JSONObject.toJSON(data));
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值