几种排序算法的java实现

 1 import java.util.Arrays;
 2 
 3 /**
 4  * 各种排序算法从小到大进行排序
 5  */
 6 public class Test {
 7 
 8     public static void main(String args[]) {
 9         int[] n = { 5, 2, 3, 4, 1 };
10         int[] n1, n2, n3;
11         n1 = n2 = n3 = Arrays.copyOf(n, n.length);
12 
13         System.out.println("原来的数组:");
14         printArray(n);
15 
16         selectionSort(n1);
17         System.out.println("
选择排序后:");
18         printArray(n1);
19 
20         bubbleSort(n2);
21         System.out.println("
冒泡排序后:");
22         printArray(n2);
23         
24         insertionSort(n3);
25         System.out.println("
插入排序后:");
26         printArray(n3);
27     }
28 
29     /** 选择排序:首先确定的是最小元素 */
30     private static void selectionSort(int number[]) {
31         for (int i = 0; i < number.length - 1; i++) {
32             // 对当前无序区间score[i......length-1]进行排序
33             for (int j = i + 1; j < number.length; j++) {
34                 if (number[i] > number[j]) {
35                     int temp = number[i];
36                     number[i] = number[j];
37                     number[j] = temp;
38                 }
39             }
40 
41         }
42     }
43 
44     /** 冒泡排序:最先确定的是最大的元素 */
45     private static void bubbleSort(int number[]) {
46         for (int i = 0; i < number.length - 1; i++) {
47             // 对当前无序区间score[0......length-i-1]进行排序
48             for (int j = 0; j < number.length - i - 1; j++) {
49                 if (number[j] > number[j + 1]) {
50                     int temp = number[j];
51                     number[j] = number[j + 1];
52                     number[j + 1] = temp;
53                 }
54             }
55         }
56     }
57 
58     /** 插入排序:不断将元素插入到已经排好序的数据(注意插入的顺序) */
59     private static void insertionSort(int[] list) {
60         for (int i = 1; i < list.length; i++) {
61             int currentElement = list[i];
62             // 把list[i]插入到list[0]~list[i-1]之间,这样list[0]~list[i]就排好序了
63             int j;
64             for (j = i - 1; j >= 0 && list[j] > currentElement; j--) {
65                 list[j + 1] = list[j];
66             }
67             // 把当前元素插入到list[j+1]
68             list[j + 1] = currentElement;
69         }
70     }
71 
72     /** 打印数组中的元素 */
73     private static void printArray(int number[]) {
74         for (int i : number) {
75             System.out.print(i + "	");
76         }
77     }
78 }

运行结果:

原文地址:https://www.cnblogs.com/happyfans/p/4343515.html