-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsort.java
More file actions
92 lines (83 loc) · 2.61 KB
/
sort.java
File metadata and controls
92 lines (83 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package Algorithm.sort;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.json.JSONArray;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static Algorithm.selection.Selection3.swap;
/**
* Created by lenovo on 2017/3/23.
*/
public class Sort {
public static void main(String[] args) throws IOException {
int[] arr = {1, 3, 5, 7, 9, 2, 4, 6, 8, 10, 11};
// quicksort(a,0,a.length-1);
int[] temArr = new int[arr.length];
mergesort(arr, temArr, 0, arr.length - 1);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + ",");
}
}
private static void mergesort(int[] arr, int[] tempArr, int left, int right) {
if (left >= right)
return;
int mid = (left + right) / 2;
mergesort(arr, tempArr, left, mid);
mergesort(arr, tempArr, mid + 1, right);
merge(arr, tempArr, left, right, mid);
}
private static void merge(int[] arr, int[] tempArr, int left, int right, int mid) {
for (int i = left; i <= right; i++) {
tempArr[i] = arr[i];
}
int cursor = left;
int index1 = left;
int index2 = mid + 1;
while (index1 <= mid && index2 <= right) {
if (tempArr[index1] <= tempArr[index2]) {
arr[cursor++] = tempArr[index1++];
} else {
arr[cursor++] = tempArr[index2++];
}
}
while (index1 <= mid) {
arr[cursor++] = tempArr[index1++];
}
while (index2 <= right) {
arr[cursor++] = tempArr[index2++];
}
}
private static void quicksort(int[] arr, int left, int right) {
if (left >= right)
return;
int pivotIndex = (left + right) / 2;
swap(arr, pivotIndex, right);
pivotIndex = partition(arr, left, right);
quicksort(arr, left, pivotIndex - 1);
quicksort(arr, pivotIndex + 1, right);
}
private static int partition(int[] arr, int left, int right) {
int pivot = arr[right];
int l = left;
int r = right-1;
while (l <= r) {
while (l <= r && arr[l] <= pivot) {
++l;
}
while (l <= r && arr[r] >= pivot) {
--r;
}
if (l < r) {
swap(arr, l, r);
}
}
swap(arr, l, right);
return l;
}
}