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 #36

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
81 changes: 81 additions & 0 deletions Sorting Algo/mergeSort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
public class MergeSort {

// Function to merge two subarrays of arr[].
// First subarray is arr[left..mid]
// Second subarray is arr[mid+1..right]
public static void merge(int[] arr, int left, int mid, int right) {
// Sizes of two subarrays to be merged
int n1 = mid - left + 1;
int n2 = right - mid;

// Temporary arrays
int[] L = new int[n1];
int[] R = new int[n2];

// Copy data to temporary arrays
for (int i = 0; i < n1; ++i)
L[i] = arr[left + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[mid + 1 + j];

// Merge the two subarrays
int i = 0, j = 0;
int k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}

// Copy remaining elements of L[], if any
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}

// Copy remaining elements of R[], if any
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}

// Main function that sorts arr[left..right] using merge()
public static void mergeSort(int[] arr, int left, int right) {
if (left < right) {
// Find the middle point
int mid = left + (right - left) / 2;

// Recursively sort the first and second halves
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);

// Merge the sorted halves
merge(arr, left, mid, right);
}
}

// Utility function to print the array
public static void printArray(int[] arr) {
for (int value : arr) {
System.out.print(value + " ");
}
System.out.println();
}

public static void main(String[] args) {
int[] numbers = {12, 11, 13, 5, 6, 7};
System.out.println("Original array:");
printArray(numbers);
mergeSort(numbers, 0, numbers.length - 1);
System.out.println("Sorted array:");
printArray(numbers);
}
}