1 package ch.hslu.exercises.sw14;
2
3
4 public class Sort {
5
6 public static void insertionSort(final int[] a) {
7 int elt;
8 int j;
9 Thread thread = new Thread();
10 for (int i = 1; i < a.length; i++) {
11 elt = a[i];
12 j = i;
13 while ((j > 0) && (a[j - 1] > elt)) {
14 a[j] = a[j - 1];
15 j--;
16 }
17 a[j] = elt;
18 }
19 }
20
21 public static void insertionSort2(final int[] a) {
22 int elt;
23 int j;
24 for (int i = 2; i < a.length; i++) {
25 elt = a[i];
26 a[0] = elt;
27 j = i;
28 while (a[j - 1] > elt) {
29 a[j] = a[j - 1];
30 j--;
31 }
32 a[j] = elt;
33 }
34 }
35
36 public static void quickSort(final char[] a, final int left, final int right) {
37 int up = left;
38 int down = right - 1;
39 char t = a[right];
40 boolean allChecked = false;
41 do {
42 while (a[up] < t) {
43 up++;
44 }
45 while ((a[down] >= t) && (down > up)) {
46 down--;
47 }
48 if (down > up) {
49 exchange(a, up, down);
50 up++;
51 down--;
52 } else {
53 allChecked = true;
54 }
55 } while (!allChecked);
56 exchange(a, up, right);
57 if (left < (up - 1)) quickSort(a, left, (up - 1));
58 if ((up + 1) < right) quickSort(a, (up + 1), right);
59 }
60
61 private static void exchange(final char[] a, final int firstIndex, final int secondIndex) {
62 char tmp;
63 tmp = a[firstIndex];
64 a[firstIndex] = a[secondIndex];
65 a[secondIndex] = tmp;
66 }
67
68 public static void selectionSort(final int[] a) {
69 for (int i = 0; i < (a.length - 1); i++) {
70 int index = i;
71 for (int j = i + 1; j < a.length; j++) {
72 if (a[j] < a[index]) {
73 index = j;
74 }
75 }
76 int temp = a[i];
77 a[i] = a[index];
78 a[index] = temp;
79 }
80 }
81
82 static void bubbleSort(int[] arr) {
83 int temp = 0;
84 for (int i = 0; i < arr.length; i++) {
85 for (int j = 1; j < (arr.length - i); j++) {
86 if (arr[j - 1] > arr[j]) {
87
88 temp = arr[j - 1];
89 arr[j - 1] = arr[j];
90 arr[j] = temp;
91 }
92
93 }
94 }
95 }
96
97 private static char[] b;
98
99 public static void mergeSort(final char[] a) {
100 b = new char[a.length];
101 mergeSort(a, 0, a.length - 1);
102 }
103
104 private static void mergeSort(final char a[], final int left, final int right) {
105 int i, j, k, m;
106 if (right > left) {
107 m = (right + left) / 2;
108 mergeSort(a, left, m);
109 mergeSort(a, m + 1, right);
110
111 for (i = left; i <= m; i++) {
112 b[i] = a[i];
113 }
114 for (j = m; j < right; j++) {
115 b[right + m - j] = a[j + 1];
116 }
117 i = left;
118 j = right;
119 for (k = left; k <= right; k++) {
120 if (b[i] <= b[j]) {
121 a[k] = b[i];
122 i++;
123 } else {
124 a[k] = b[j];
125 j--;
126 }
127 }
128 }
129 }
130
131 }
132
133