This repository has been archived by the owner on May 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 773
/
merge-sort.java
79 lines (68 loc) · 1.63 KB
/
merge-sort.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
//Java program for implementation of Merge Sort
import java.util.*;
class MergeSortApp
{
private int[] arr;
public MergeSortApp()
{
arr = new int[]{12,54,222,54622,10,169,30}; //Array to sort
}
//Function to display/Print Array
public void printArray()
{
for (int i=0;i<arr.length;i++)
{
System.out.print(arr[i]+ " ");
}
System.out.println();
}
//Function called by main()
public void mergesort()
{
int[] wr = new int[arr.length]; //Provides workspace
recMergeSort(wr,0,wr.length-1);
}
//Recursive function to divide array in halves
public void recMergeSort(int[] wr,int lowBound,int uppBound)
{
if (lowBound == uppBound)
return;
else
{
int mid = (lowBound+uppBound)/2; //find midpoint
recMergeSort(wr,lowBound,mid); //Sort low half
recMergeSort(wr,mid+1,uppBound); // Sort high half
merge(wr,lowBound,mid+1,uppBound); //merge them
}
}
//Function to merge sorted Arrays
public void merge(int[] wr,int lowptr,int highptr, int uppBound)
{
int j=0;
int lowBound = lowptr;
int mid = highptr-1;
int n = uppBound-lowBound+1;
while (lowptr<=mid && highptr<=uppBound)
{ if (arr[lowptr]<arr[highptr])
wr[j++] = arr[lowptr++];
else
wr[j++] = arr[highptr++];
}
while (lowptr<=mid)
wr[j++] = arr[lowptr++];
while(highptr<=uppBound)
wr[j++] = arr[highptr++];
for (j=0;j<n;j++)
arr[lowBound+j] = wr[j];
}
}
class MergeSort
{ //Driver code to test above code
public static void main(String[] args)
{
MergeSortApp ob = new MergeSortApp(); //creates object
ob.printArray(); //Displays Array before sorting
ob.mergesort();
ob.printArray();
}
}