java实现各种排序算法

java实现各种排序算法

 1 import java.util.Arrays;
 2 
 3 public class SomeSort {
 4 
 5     public static void main(String[] args) {
 6         // TODO Auto-generated method stub
 7 
 8         int[] a = { 1, 5, 6, 2, 7, 4, 9 };// 升序
 9         // selectionSort(a);
10         //bubbleSort(a);
11         insertSort(a);
12         System.out.println(Arrays.toString(a));
13     }
14 
15     // 选择排序
16     public static void selectionSort(int[] a) {
17 
18         for (int i = 0; i < a.length; i++) {
19             int min = a[i], temp;
20             for (int j = i; j < a.length; j++) {
21                 if (min > a[j]) {
22                     temp = min;
23                     min = a[j];
24                     a[j] = temp;
25                 }
26             }
27             a[i] = min;
28         }
29     }
30 
31     // 冒泡排序
32     public static void bubbleSort(int[] a) {
33         int temp;
34         for (int i = 0; i < a.length; i++) {
35 
36             for (int j = 0; j < a.length - i - 1; j++) {
37                 if (a[j] > a[j + 1]) {
38                     temp = a[j];
39                     a[j] = a[j + 1];
40                     a[j + 1] = temp;
41                 }
42             }
43         }
44     }
45     
46     //插入排序
47     public static void insertSort(int[] a){
48         int temp;
49         for(int i = 1;i < a.length;i ++){
50             for(int j = i;j > 0;j --){
51                 if(a[j] < a[j - 1]){
52                     temp = a[j];
53                     a[j] = a[j - 1];
54                     a[j - 1] = temp;
55                 }
56             }
57         }
58     }
59 
60     
61 
62 }
原文地址:https://www.cnblogs.com/anqiang1995/p/7496360.html