-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathMergeSort.java
119 lines (56 loc) · 1.68 KB
/
MergeSort.java
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import java.util.Scanner;
public class MergeSort{
public static void main(String a[]){
int temp;
Scanner sc=new Scanner (System.in);
System.out.println("Enter N ( how many numbers to be sorted)");
int n = sc.nextInt();
int [] list=new int[n];
System.out.println("Enter "+n+ " numbers 1 by 1");
for (int i=0 ; i<n; i++)
{
int number = sc.nextInt();
list[i]=number;
}
System.out.println("List before sorting \n");
for(int i = 0; i < list.length; i++)
System.out.print( list[i]+" ");
System.out.println();
mergeSort(list,0, list.length-1);
System.out.print("List after sorting \n");
for(int i = 0; i < list.length; i++)
System.out.print(list[i]+" ");
System.out.println();
}
public static void mergeSort(int list[],int low, int high){
if (low >= high)
{
return;
}
int middle = (low + high) / 2;
mergeSort(list, low, middle);
mergeSort(list, middle + 1, high);
merge(list, low,middle,high);
}
private static void merge(int list[], int low, int middle, int high)
{
int IstList_end= middle;
int IIndList_start = middle + 1;
int l=low;
while ((l <= IstList_end) && (IIndList_start <= high))
{
if (list[low] < list[IIndList_start]) {
low++;
} else {
int temp = list[IIndList_start];
for (int j = IIndList_start-1; j >= low; j--) {
list[j+1] = list[j];
}
list[low] = temp;
low++;
IstList_end++;
IIndList_start++;
}
}
}
}