各种排序算法

基础才是最重要的, 好久不写排序了,今天写了一下还是各种报错。。。。

要养成习惯,每天至少做一道算法题

 

 1 //复习各种排序
 2 public class SortApp {
 3 
 4     public static void main(String[] args) {
 5         int[] a = {5,23,7,18,56,2,36,5,3,9,6,4,1};
 6         SortApp app = new SortApp();
 7         //app.quickSort(a);
 8         //app.selectSort(a);
 9         //app.insertSort(a);
10         app.bubbleSort(a);
11         app.display(a);
12     }
13     
14     //快速
15     void quickSort(int[] a){
16         quickSort(a, 0, a.length - 1);
17     }
18     
19     private void quickSort(int[] a, int left, int right){
20         if(left >= right) return;
21         int pivot = left;
22         int i = left, j = right + 1;
23         
24         while(i<j){
25             while(a[++i] < a[pivot] && i < right);
26             while(a[--j] > a[pivot] && j > 0);
27             if(i<j)swap(a, i, j);
28         }
29         swap(a,pivot, j);
30         
31         quickSort(a, left, j-1);
32         quickSort(a, j+1, right);
33     }
34     
35     //冒泡
36     void bubbleSort(int[] a){
37         for(int i = 0; i < a.length; i++){
38             for(int j = 1; j < a.length - i; j++){
39                 if(a[j-1] >= a[j]){
40                     swap(a,j-1,j);
41                 }
42             }
43         }
44     }
45     
46     //插入
47     void insertSort(int[] a){
48         for(int i = 1; i < a.length; i++){
49             int current = a[i];
50             //pointer for the previous element of i
51             int j = i-1;
52             while(j>=0 && a[j] > current){
53                 a[j+1] = a[j];
54                 j--;
55             }
56             
57             //now j points to the element which is smaller than a[i]
58             a[j+1] = current;
59         }
60     }
61     
62     //选择
63     void selectSort(int[] a){
64         for(int i = 0; i < a.length; i++){
65             int min = i;
66             for(int j = i+1; j < a.length; j++){
67                 if(a[j] < a[min]) min = j;
68             }
69             swap(a, i, min);
70         }
71     }
72     
73     private void swap(int[] a, int i, int j){
74         int tmp = a[i];
75         a[i] = a[j];
76         a[j] = tmp;
77     }
78     
79     private void display(int[] a){
80         for(int i: a){
81             System.out.print(" " + i);
82         }
83         System.out.println("");
84     }
85 }

 

posted @ 2015-11-20 16:44  蟹粉小笼包  阅读(188)  评论(0编辑  收藏  举报