堆排序关系
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));
}
}
堆排序关系parent = (i-1) / 2left = 2i + 1right = 2i+2public class HeapSort { public static void main(String []args){ int tree [] = {10,3,4,9,11}; int n = 5; heapSort(tree...