forked from sanketpatil02/Code-Overflow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram to Sort an Array
More file actions
97 lines (92 loc) · 2.42 KB
/
Program to Sort an Array
File metadata and controls
97 lines (92 loc) · 2.42 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
95
96
#Ascending Sorting of an Array Using Merge Sort
import java.util.*;
public class Main
{
public static void main(String[] args) {
int arr[] = {1,-4,9,3,2,13,-5,16};
int len = arr.length;
Main m = new Main();
m.sort(arr);
for(int i=0;i<len;i++){
System.out.print(arr[i]+" ");
}
}
public void sort(int[] array){
if(array.length<2) return;
int middle = array.length/2;
int left[] = new int[middle];
for(int i=0;i<middle;i++){
left[i] = array[i];
}
int right[] = new int[array.length-middle];
for(int i=middle;i<array.length;i++){
right[i-middle] = array[i];
}
sort(left);
sort(right);
merge(left,right,array);
}
private void merge(int[] left,int[] right,int[] result ){
int i=0,j=0,k=0;
while(i<left.length&&j<right.length){
if(left[i]<=right[j]){
result[k++] = left[i++];
}
else{
result[k++] = right[j++];
}
}
while(i<left.length){
result[k++] = left[i++];
}
while (j<right.length){
result[k++] = right[j++];
}
}
}
#Descending Sorting of an Array Using Merge Sort
import java.util.*;
public class Main
{
public static void main(String[] args) {
int arr[] = {1,-4,9,3,2,13,-5,16};
int len = arr.length;
Main m = new Main();
m.sort(arr);
for(int i=0;i<len;i++){
System.out.print(arr[i]+" ");
}
}
public void sort(int[] array){
if(array.length<2) return;
int middle = array.length/2;
int left[] = new int[middle];
for(int i=0;i<middle;i++){
left[i] = array[i];
}
int right[] = new int[array.length-middle];
for(int i=middle;i<array.length;i++){
right[i-middle] = array[i];
}
sort(left);
sort(right);
merge(left,right,array);
}
private void merge(int[] left,int[] right,int[] result ){
int i=0,j=0,k=0;
while(i<left.length&&j<right.length){
if(left[i]>right[j]){
result[k++] = left[i++];
}
else{
result[k++] = right[j++];
}
}
while(i<left.length){
result[k++] = left[i++];
}
while (j<right.length){
result[k++] = right[j++];
}
}
}