Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merge Sort Implementation #16

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions merge_sort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/* Function to merge the subarrays of a[] */
void merge(int a[], int beg, int middle, int end)
{
int i, j, k;
int n1 = middle - begining + 1;
int n2 = end - middle;

int LeftArray[n1], RightArray[n2]; //temporary arrays

/* copy data to temp arrays */
for (int i = 0; i < n1; i++)
LeftArray[i] = a[begining + i];
for (int j = 0; j < n2; j++)
RightArray[j] = a[middle + 1 + j];

i = 0, /* initial index of first sub-array */
j = 0; /* initial index of second sub-array */
k = begining; /* initial index of merged sub-array */

while (i < n1 && j < n2)
{
if(LeftArray[i] <= RightArray[j])
{
a[k] = LeftArray[i];
i++;
}
else
{
a[k] = RightArray[j];
j++;
}
k++;
}
while (i<n1)
{
a[k] = LeftArray[i];
i++;
k++;
}

while (j<n2)
{
a[k] = RightArray[j];
j++;
k++;
}
}