Steps:
Ask the user for the number of orders.
Read timestamps (as integers).
Sort them using Merge Sort.
Analyze time complexity vs. other sorting algorithms.
Steps:
Ask the user for the number of orders.
Read timestamps (as integers).
Sort them using Merge Sort.
Analyze time complexity vs. other sorting algorithms.
Merge Sort:
Best Case: O(n log n)
Average Case: O(n log n)
Worst Case: O(n log n)
Stable and efficient for large datasets.
Comparison with Other Sorting Techniques:
| Algorithm | Best Case | Average Case | Worst Case | Stable | Suitable for 1M+? |
|------------------|-----------|--------------|------------|--------|-------------------|
| Bubble Sort | O(n) | O(n²) | O(n²) | Yes | ❌ Too slow |
| Selection Sort | O(n²) | O(n²) | O(n²) | No | ❌ Too slow |
| Insertion Sort | O(n) | O(n²) | O(n²) | Yes | ❌ Too slow |
| Merge Sort | O(n log n)| O(n log n) | O(n log n) | Yes | ✅ Very good |
| Quick Sort | O(n log n)| O(n log n) | O(n²) | No | ✅ (with care) |
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Merge function to combine two sorted halves
void merge(long arr[], long left, long mid, long right) {
long n1 = mid - left + 1;
long n2 = right - mid;
// Temporary arrays
long *L = (long *)malloc(n1 * sizeof(long));
long *R = (long *)malloc(n2 * sizeof(long));
for (long i = 0; i < n1; i++)
L[i] = arr[left + i];
for (long j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];
// Merge the temp arrays back into arr
long i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j])
arr[k++] = L[i++];
else
arr[k++] = R[j++];
}
// Copy remaining elements
while (i < n1)
arr[k++] = L[i++];
while (j < n2)
arr[k++] = R[j++];
free(L);
free(R);
}
// Recursive merge sort
void mergeSort(long arr[], long left, long right) {
if (left < right) {
long mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
int main() {
long n;
printf("Enter number of customer orders: ");
scanf("%ld", &n);
if (n > 1000000) {
printf("Error: Maximum 1,000,000 orders allowed.\n");
return 1;
}
long *timestamps = (long *)malloc(n * sizeof(long));
if (!timestamps) {
printf("Memory allocation failed!\n");
return 1;
}
printf("Enter timestamps (as integers):\n");
for (long i = 0; i < n; i++) {
scanf("%ld", ×tamps[i]);
}
clock_t start = clock();
mergeSort(timestamps, 0, n - 1);
clock_t end = clock();
printf("\nSorted timestamps:\n");
for (long i = 0; i < n; i++) {
printf("%ld ", timestamps[i]);
}
double time_taken = ((double)(end - start)) / CLOCKS_PER_SEC;
printf("\n\nMerge Sort completed in %.6f seconds.\n", time_taken);
free(timestamps);
return 0;
}
Output:
Enter number of customer orders: 8
Enter timestamps (as integers):
202308121530
202307011200
202309101045
202301011230
202305051500
202304091000
202309101040
202302151430
Sorted timestamps:
202301011230 202302151430 202304091000 202305051500 202307011200 202308121530 202309101040 202309101045
Merge Sort completed in 0.000015 seconds.