public class HeapSort {
public static void main(String[] args) {
int[] input = {1,2,3,4,5,6,7,8,9,10,11,12,13,14};
//构建大根堆,从编号k/2-1开始调整
for(int len=input.length/2-1; len>=0; len--){
adjustMaxHeapSort(input,len,input.length-1);
}
for(int i=0;i<input.length;i++){
System.out.print(input[i]);
System.out.print(" ");
}
}
//调整成大根堆
public static void adjustMaxHeapSort(int[] input, int pos, int length){
int temp;
int child;
for(temp=input[pos]; 2*pos+1<=length; pos=child){
child=2*pos+1;
if(child<length && input[child]<input[child+1]){
child++;
}
if(input[child]>temp){
input[pos]=input[child];
input[child]=temp;
}else{
break;
}
}
}
}
//冒泡排序
static void bubbleSort(int[] nums) {
int temp = 0;
for (int i = 0; i < nums.length - 1; i++) {
for (int j = nums.length - 1; j > i; j--) {
if (nums[j] < nums[j - 1]) {
temp = nums[j];
nums[j] = nums[j - 1];
nums[j - 1] = temp;
}
}
}
}
// 快速排序
static void quickSort(int left, int right, int[] nums) {
if (left < right) {
int pivot = nums[left];
int low = left;
int high = right;
while (low < high) {
while (low < high && nums[high] >= pivot) {
high--;
}
if (nums[high] < pivot)
nums[low] = nums[high];
while (low < high && nums[low] <= pivot) {
low++;
}
if (nums[low] > pivot)
nums[high] = nums[low];
}
nums[low] = pivot;
quickSort(left, low - 1, nums);
quickSort(low + 1, right, nums);
}
}
//归并排序
public class MyMergeSort {
public static void main(String[] args) {
int[] num = { 9, 38, 37, 6, 5, 4, 33, 2, 1 };
sort(num, 0, num.length - 1);
for (int i = 0; i < num.length; i++) {
System.out.print(num[i]);
System.out.print(" ");
}
}
public static void sort(int[] num, int low, int high) {
if(num==null||num.length==0)
return;
int mid = (low + high) / 2;
if (low < high) {
sort(num, low, mid);
sort(num, mid + 1, high);
merge(num, low, high, mid);
}
}
private static void merge(int[] num, int low, int high, int mid) {
int[] temp = new int[high - low + 1];
int i = low, j = mid + 1;
int index = 0;
while (i <= mid && j <=high) {
if (num[i] <= num[j])
temp[index++] = num[i++];
else
temp[index++] = num[j++];
}
while (i <= mid)
temp[index++] = num[i++];
while (j <=high)
temp[index++] = num[j++];
// temp数组中的元素覆盖num中的元素
int index2 = 0;
for (int k = low; k <= high; k++)
num[k] = temp[index2++];
}
}
//二分查找
static int binaryFind(int[] n, int key, int left, int right) {
if (left > right) {
return -1;
}
int low = left;
int high = right;
int mid = 0;
while (low <= high) {
mid = (low + high) / 2;
if (n[mid] == key)
return mid;
else if (n[mid] < key) {
low = mid + 1;
} else if (n[mid] > key) {
high = mid - 1;
}
}
return -1;
}