package com.heidan.test;
import java.util.Arrays;
public class Review03 {
public static void main(String[] args) {
int[] arr = {15,35,95,65,75};
// bubbleSort(arr);
// quickSort(arr,0,arr.length-1);
// selectSort(arr);
// insertSort(arr);
// shellSort(arr);
// mergeSort(arr,0,args.length-1);
heapSort(arr);
System.out.println(Arrays.toString(arr));
}
//冒泡排序
public static void bubbleSort(int[] arr){
for (int i=0;i<arr.length;i++){
for (int j=0;j<arr.length-1-i;j++){
if (arr[j]>arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
//快速排序
public static void quickSort(int[] arr,int start,int end){
if (start<end){
int low = start;
int high = end;
int standard = arr[start];
while (low<high){
while (low<high && standard<arr[high]){
high--;
}
arr[low] = arr[high];
while (low<high && standard>=arr[low]){
low++;
}
arr[high] = arr[low];
}
arr[low] = standard;
quickSort(arr,start,low);
quickSort(arr,low+1,high);
}
}
//选择排序
public static void selectSort(int[] arr){
for (int i=0;i<arr.length;i++){
int minIndex = i;
int min = arr[i];
for (int j=i+1;j<arr.length;j++){
if (min>arr[j]){
minIndex = j;
min = arr[j];
}
}
if (minIndex!=i){
arr[minIndex] = arr[i];
arr[i] = min;
}
}
}
//插入排序
public static void insertSort(int[] arr){
for (int i=1;i<arr.length;i++){
if (arr[i]<arr[i-1]){
int temp = arr[i];
int j;
for (j=i-1;i>0 && temp<arr[j];j--){
arr[j+1] = arr[j];
}
arr[j+1] = temp;
}
}
}
希尔排序(缩小增量排序)
public static void shellSort(int[] arr){
for (int d=arr.length/2;d>0;d/=2){
for (int i=d;i<arr.length;i++){
for (int j = i-d;j>=0;j-=d){
if (arr[j]>arr[j+d]){
int temp = arr[j];
arr[j] = arr[j+d];
arr[j+d] = temp;
}
}
}
}
}
//归并排序
public static void mergeSort(int[] arr,int low,int high){
int middle = (low+high)/2;
if (low<high){
mergeSort(arr,low,middle);
mergeSort(arr,middle+1,high);
merge(arr,low,middle,high);
}
}
public static void merge(int[] arr,int low,int middle,int high){
int[] temp = new int[high-low+1];
int index = 0;
int i = low;
int j = middle+1;
while (i<=middle && j<=high){
if (arr[i]<=arr[j]){
temp[index] = arr[i];
i++;
}else {
temp[index] = arr[j];
j++;
}
index++;
}
while (j<=high){
temp[index] = arr[j];
j++;
index++;
}
while (i<=middle){
temp[index] = arr[i];
i++;
index++;
}
for (int k=0;k<temp.length;k++){
arr[low+k] = temp[k];
}
}
//堆排序
public static void heapSort(int[] arr){
int start = (arr.length-1)/2;
for (int i=start;i>=0;i--){
maxHeap(arr,arr.length,i);
}
for (int i=arr.length-1;i>0;i--){
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
maxHeap(arr,i,0);
}
}
public static void maxHeap(int[] arr,int size,int index){
int leftNode = 2*index+1;
int rightNode = 2*index+2;
int max = index;
if (leftNode<size && arr[leftNode]>arr[max]){
max = leftNode;
}
if (rightNode<size && arr[rightNode]>arr[max]){
max = rightNode;
}
if (max!=index){
int temp = arr[index];
arr[index] = arr[max];
arr[max] = temp;
maxHeap(arr,size,max);
}
}
}