-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSort.java
More file actions
71 lines (60 loc) · 1.36 KB
/
Sort.java
File metadata and controls
71 lines (60 loc) · 1.36 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
package practice;
import java.util.Arrays;
class Sort {
private int[] array;
private void swap(int n1, int n2){
int temp = array[n1];
array[n1] = array[n2];
array[n2] = temp;
}
private int[] quickSort(int[] arr) {
this.array = arr;
return quickSort(0,array.length-1);
}
private int[] quickSort(int lo,int hi){
int p = quickPartition(lo,hi);
if (lo<p-1) quickSort(lo, p-1);
if (p<hi) quickSort(p,hi);
return array;
}
private int quickPartition(int left,int right) {
int i = left;
int j = right;
int pivot = array[(left+right)/2];
while (i<=j){
while (array[i]<pivot) i++;
while (array[j]>pivot) j--;
if (i<=j) {
swap(i,j);
i++;
j--;
}
}
return i;
}
void mergeSort(int[] arr) {
this.array = arr;
mergeSort(0,arr.length-1);
}
private void mergeSort(int lo, int hi) {
if (lo<hi){
int mid = (lo+hi)/2;
mergeSort(lo, mid);
mergeSort(mid+1,hi);
merge(lo,mid,hi);
}
}
private void merge(int lo, int mid, int hi) {
int[] left = Arrays.copyOfRange(array, lo, mid+1);
int[] right = Arrays.copyOfRange(array, mid+1, hi+1);
int i = 0;
int j = 0;
int k = lo;
while (i< left.length && j<right.length){
if (left[i]< right[j]) array[k++] = left[i++];
else array[k++] = right[j++];
}
while (i<left.length) array[k++] = left[i++];
while (j<right.length) array[k++] = right[j++];
}
}