八大排序算法的Java代码实现

简单插入排序

选择排序

冒泡排序

快速排序

希尔排序

归并排序

堆排序

 1 public class HeapSort {
 2     private static void maxHeapDown(int[] a, int start, int end){
 3         int father = start;
 4         int child = 2 * father + 1; // 左孩子
 5         while (child <= end){
 6             if (child < end && a[child] < a[child + 1]){
 7                 child++;  // 如果右孩子大,将左孩子变为右孩子
 8             }
 9             if (a[father] >= a[child]){
10                 break;
11             }else {
12                 int tmp = a[father];
13                 a[father] = a[child];
14                 a[child] = tmp;
15             }
16             father = child;
17             child = 2 * father + 1;
18         }
19     }
20     private static void heapSortAsc(int[] a){
21         int i;
22         int n = a.length;
23         for (i = n / 2 -1; i >= 0; i--){  // 从最后一个非终端节点开始,逐个向上遍历
24             maxHeapDown(a, i, n-1);
25         }
26         for (i = n - 1; i > 0; i--){
27             int tmp = a[0];
28             a[0] = a[i];
29             a[i] = tmp;
30             maxHeapDown(a, 0, i-1);
31         }
32     }
33     public static void main(String[] args){
34         int[] a = {9,2,5,4,7,3,8,0,1,6};
35         heapSortAsc(a);
36         for (int i :a){
37             System.out.print(i + " ");
38         }
39     }
40 }

基数排序

猜你喜欢

转载自www.cnblogs.com/0820LL/p/9559634.html