Skip to content

Commit 1219550

Browse files
committed
quickSort bubbleSort
1 parent 52e599c commit 1219550

2 files changed

Lines changed: 65 additions & 0 deletions

File tree

src/com/java/practice/sort/BubbleSort.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,31 @@
44
* Created by richard02.zhang on 18/1/26.
55
*/
66
public class BubbleSort {
7+
8+
private static void swap(int[] arr, int x, int y) {
9+
int temp = arr[x];
10+
arr[x] = arr[y];
11+
arr[y] = temp;
12+
}
13+
14+
private static void bubbleSort(int[] arr) {
15+
if (null == arr || 0 == arr.length) {
16+
return;
17+
}
18+
for (int i = 0; i < arr.length; i++){
19+
for (int j = 0; j < arr.length; j++) {
20+
if (arr[i] <= arr[j]) {
21+
swap(arr, i, j);
22+
}
23+
}
24+
}
25+
}
26+
27+
public static void main(String[] args) {
28+
int[] arr = {4, 5, 2, 2, 7, 1, 9, 8};
29+
bubbleSort(arr);
30+
for (int i = 0; i < arr.length; i++){
31+
System.out.println(arr[i]);
32+
}
33+
}
734
}

src/com/java/practice/sort/QuickSort.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,42 @@
44
* Created by richard02.zhang on 18/1/26.
55
*/
66
public class QuickSort {
7+
8+
private static void swap(int[] arr, int x, int y) {
9+
int temp = arr[x];
10+
arr[x] = arr[y];
11+
arr[y] = temp;
12+
}
13+
14+
private static int partition(int[] arr, int begin, int end) {
15+
int index = begin;
16+
int pivot = arr[end];
17+
for (int i = begin; i < arr.length; i++) {
18+
if (arr[i] < pivot ) {
19+
swap(arr, index, i);
20+
index++;
21+
}
22+
}
23+
swap(arr, end, index);
24+
return index;
25+
}
26+
27+
private static void quickSort(int[] arr, int begin, int end) {
28+
if (null == arr || arr.length == 0) {
29+
return;
30+
}
31+
if (begin < end) {
32+
int index = partition(arr, begin, end);
33+
quickSort(arr, begin, index - 1);
34+
quickSort(arr, index + 1, end);
35+
}
36+
}
37+
38+
public static void main(String[] args) {
39+
int[] arr = {5, 4, 4, 3, 3, 2, 1};
40+
quickSort(arr, 0, arr.length - 1);
41+
for (int i = 0; i < arr.length; i++){
42+
System.out.println(arr[i]);
43+
}
44+
}
745
}

0 commit comments

Comments
 (0)