1 public class Demo {
2
3 public static void main(String[] args) {
4 int[] arr = new int[10];
5 for (int i = 0; i < arr.length; i++) {
6 Random rd = new Random();
7 arr[i] = rd.nextInt(100);
8 }
9 System.out.println("需排序數組-->");
10 for (int j = 0; j < arr.length; j++) {
11 System.out.print(arr[j] + "\t");
12 }
13 System.out.println();
14 System.out.println();
15
16 //選擇排序
17 for (int i = 1; i < arr.length; i++) {
18 int max = 0;
19 for (int j = 0; j <= arr.length-i; j++) {
20 if(arr[j]>arr[max]){
21 max = j;
22 }
23 }
24 int temp = arr[arr.length-i];
25 arr[arr.length-i] = arr[max];
26 arr[max] = temp;
27 }
28 System.out.println("選擇排序結果-->");
29 for (int j = 0; j < arr.length; j++) {
30 System.out.print(arr[j] + "\t");
31 }
32 System.out.println();
33
34 //冒泡排序
35 for (int i = 1; i < arr.length; i++) {
36 for (int j = 0; j < arr.length-1; j++) {
37 if (arr[j+1]<arr[j]) {
38 int temp = arr[j+1];
39 arr[j+1] = arr[j];
40 arr[j] = temp;
41 }
42 }
43 }
44 System.out.println("冒泡排序結果-->");
45 for (int j = 0; j < arr.length; j++) {
46 System.out.print(arr[j] + "\t");
47 }
48 System.out.println();
49
50 //快速排序
51 quickSort(arr, 0, arr.length-1);
52 System.out.println("快速排序結果-->");
53 for (int j = 0; j < arr.length; j++) {
54 System.out.print(arr[j] + "\t");
55 }
56 System.out.println();
57
58 //直接插入排序
59 for (int i = 1; i < arr.length; i++) {
60 int temp = arr[i];
61 int j;
62 for (j = i - 1; j >= 0 && arr[j] > temp; j--) {
63 arr[j + 1] = arr[j];
64 }
65 arr[j + 1] = temp;
66 }
67 System.out.println("直接插入排序結果-->");
68 for (int j = 0; j < arr.length; j++) {
69 System.out.print(arr[j] + "\t");
70 }
71 System.out.println();
72
73 //使用sort()排序
74 Arrays.sort(arr);
75 System.out.println("使用sort()排序結果-->");
76 for (int j = 0; j < arr.length; j++) {
77 System.out.print(arr[j] + "\t");
78 }
79 System.out.println();
80
81 }
82
83 public static void quickSort(int[] a, int l, int r) {
84
85 if (l < r) {
86 int i,j,x;
87
88 i = l;
89 j = r;
90 x = a[i];
91 while (i < j) {
92 while(i < j && a[j] > x){
93 j--; // 從右向左找第一個小於x的數
94 }
95 if(i < j){
96 a[i++] = a[j];
97 }
98 while(i < j && a[i] < x){
99 i++; // 從左向右找第一個大於x的數
100 }
101 if(i < j){
102 a[j--] = a[i];
103 }
104 }
105 a[i] = x;
106 quickSort(a, l, i-1); /* 遞歸調用 */
107 quickSort(a, i+1, r); /* 遞歸調用 */
108 }
109 }
110
111 }