Merge Sort
Mon Nov 18 2024 17:54:53 GMT+0000 (Coordinated Universal Time)
Saved by @badram123
import java.util.*; class Solution { private static void merge(int[] arr, int low, int mid, int high) { ArrayList<Integer> temp = new ArrayList<>(); int left = low; int right = mid + 1; while (left <= mid && right <= high) { if (arr[left] <= arr[right]) { temp.add(arr[left]); left++; } else { temp.add(arr[right]); right++; } } while (left <= mid) { temp.add(arr[left]); left++; } while (right <= high) { temp.add(arr[right]); right++; } for (int i = low; i <= high; i++) { arr[i] = temp.get(i - low); } } public static void mergeSort(int[] arr, int low, int high) { if (low >= high) return; int mid = (low + high) / 2; mergeSort(arr, low, mid); mergeSort(arr, mid + 1, high); merge(arr, low, mid, high); } } public class tUf { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = 7; int arr[] = { 9, 4, 7, 6, 3, 1, 5 }; System.out.println("Before sorting array: "); for (int i = 0; i < n; i++) { System.out.print(arr[i] + " "); } System.out.println(); Solution.mergeSort(arr, 0, n - 1); System.out.println("After sorting array: "); for (int i = 0; i < n; i++) { System.out.print(arr[i] + " "); } System.out.println(); } } import matplotlib.pyplot as plt # Example data points: input sizes and their corresponding execution times input_sizes = [1000, 5000, 10000, 50000, 100000] execution_times_quick = [1.8, 9.5, 21.3, 110.7, 250.3] # Replace these with actual results plt.plot(input_sizes, execution_times_quick, marker='o', linestyle='-', color='r', label='Quick Sort') plt.title('Quick Sort Time Complexity') plt.xlabel('Input Size (n)') plt.ylabel('Execution Time (ms)') plt.grid(True) plt.legend() plt.show()
Comments