-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProject2.java
More file actions
95 lines (67 loc) · 1.4 KB
/
Project2.java
File metadata and controls
95 lines (67 loc) · 1.4 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
93
94
package project2;
public class Project2 {
public static void main(String[] args) {
}
public static void insertionSort(int[] a) {
System.out.println("Start insertion Sort");
for (int j = 1; j < a.length; j++) {
int key = a[j];
int i = j-1;
while (i >= 0 && a[i]> key) {
a[i +1] =a[i];
i = i -1;
}
a[i +1]= key;
}
}
public static void mergeSort(int[] a) {
System.out.println("Start merge Sort");
sort( a, 0, (a.length-1));
}
static void merge(int a[], int left, int middle, int right ){
int temp1, temp2;
temp1 = middle - left +1;
temp2 = right - middle;
int [] Left = new int[temp1];
int [] Right = new int[temp2];
for (int i = 0; i < temp1; ++i) {
Left[i] = a[left +i];
}
for(int j = 0; j < temp2; ++j) {
Right[j] = a[middle + 1 +j];
}
int i, j, key;
i = 0;
j = 0;
key = left;
while(i < temp1 && j < temp2) {
if(Left[i] <= Right[j]) {
a[key] = Left[i];
i++;
}else {
a[key] = Right[j];
j++;
}
key++;
}
while (i < temp1) {
a[key] = Left[i];
i++;
key++;
}
while (j < temp2) {
a[key] = Right[j];
j++;
key++;
}
}
static void sort(int arr[], int left, int right)
{
if (left < right) {
int mid =left+ (right-left)/2;
sort(arr, left, mid);
sort(arr, (mid + 1), right);
merge(arr, left, mid, right);
}
}
}