|
| 1 | +/* |
| 2 | + * Algorithm Name |
| 3 | +Merge Sort |
| 4 | + |
| 5 | +Programming Language |
| 6 | +Java |
| 7 | +
|
| 8 | +Category |
| 9 | +Sorting |
| 10 | +
|
| 11 | +Difficulty Level |
| 12 | +Medium |
| 13 | +
|
| 14 | +* Algorithm Description : |
| 15 | +
|
| 16 | +1. Problem it solves: |
| 17 | +-> Efficiently sorts an array or list in ascending order. |
| 18 | +-> Works better than simple algorithms (like Bubble Sort or Insertion Sort) for large datasets. |
| 19 | +
|
| 20 | +2. Approach / Idea: |
| 21 | +-> Merge Sort is a Divide and Conquer algorithm. |
| 22 | +-> Steps: |
| 23 | + - Divide: Split the array into two halves. |
| 24 | + - Conquer: Recursively sort the two halves. |
| 25 | + - Combine: Merge the two sorted halves into one sorted array. |
| 26 | +
|
| 27 | +3. Complexity: |
| 28 | +Time: |
| 29 | +-> Best Case: O(n log n) |
| 30 | +-> Average Case: O(n log n) |
| 31 | +-> Worst Case: O(n log n) |
| 32 | +
|
| 33 | +Space: |
| 34 | +-> O(n) for temporary arrays during merging. |
| 35 | +
|
| 36 | +* Author : Surya Pratap Singh |
| 37 | +*/ |
| 38 | + |
| 39 | +public class MergeSort { |
| 40 | + void merge(int arr[], int left, int mid, int right) { |
| 41 | + int n1 = mid - left + 1; |
| 42 | + int n2 = right - mid; |
| 43 | + |
| 44 | + int L[] = new int[n1]; |
| 45 | + int R[] = new int[n2]; |
| 46 | + |
| 47 | + for (int i = 0; i < n1; ++i) |
| 48 | + L[i] = arr[left + i]; |
| 49 | + for (int j = 0; j < n2; ++j) |
| 50 | + R[j] = arr[mid + 1 + j]; |
| 51 | + |
| 52 | + int i = 0, j = 0, k = left; |
| 53 | + while (i < n1 && j < n2) { |
| 54 | + if (L[i] <= R[j]) { |
| 55 | + arr[k] = L[i]; |
| 56 | + i++; |
| 57 | + } else { |
| 58 | + arr[k] = R[j]; |
| 59 | + j++; |
| 60 | + } |
| 61 | + k++; |
| 62 | + } |
| 63 | + |
| 64 | + while (i < n1) { |
| 65 | + arr[k] = L[i]; |
| 66 | + i++; |
| 67 | + k++; |
| 68 | + } |
| 69 | + |
| 70 | + while (j < n2) { |
| 71 | + arr[k] = R[j]; |
| 72 | + j++; |
| 73 | + k++; |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + // Function to sort array using merge sort |
| 78 | + void sort(int arr[], int left, int right) { |
| 79 | + if (left < right) { |
| 80 | + int mid = left + (right - left) / 2; |
| 81 | + |
| 82 | + sort(arr, left, mid); |
| 83 | + sort(arr, mid + 1, right); |
| 84 | + |
| 85 | + merge(arr, left, mid, right); |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + // Driver function |
| 90 | + public static void main(String args[]) { |
| 91 | + int arr[] = {12, 11, 13, 5, 6, 7}; |
| 92 | + |
| 93 | + MergeSort ob = new MergeSort(); |
| 94 | + ob.sort(arr, 0, arr.length - 1); |
| 95 | + |
| 96 | + System.out.println("Sorted array:"); |
| 97 | + for (int num : arr) |
| 98 | + System.out.print(num + " "); |
| 99 | + } |
| 100 | +} |
0 commit comments