-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path25_merge_sort.c
More file actions
69 lines (57 loc) · 1.59 KB
/
25_merge_sort.c
File metadata and controls
69 lines (57 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include<stdio.h>
// Function to Sort Array using Merge Sort Algorithm
void merge_sort(int arr[], int low, int high)
{
int mid;
if (low < high)
{
mid = (low + high) / 2;
merge_sort(arr, low, mid);
merge_sort(arr, mid + 1, high);
merge(arr, low, mid, high);
}
}
// Function to Merge Sub-Arrays into Final Sorted Array
void merge(int arr[], int low, int mid, int high)
{
int sorted_array[10];
int left_index, right_index, final_index, index;
left_index = final_index = low;
right_index = mid + 1;
while(left_index <= mid && right_index <= high)
if(arr[left_index] < arr[right_index])
sorted_array[final_index++] = arr[left_index++];
else
sorted_array[final_index++] = arr[right_index++];
while(left_index <= mid)
sorted_array[final_index++] = arr[left_index++];
while(right_index <= high)
sorted_array[final_index++] = arr[right_index++];
for (index = low; index <= high; index++)
arr[index] = sorted_array[index];
}
int main()
{
int arr[10];
int n, index;
printf("Enter Number of Elements : ");
scanf("%d", &n);
if(n > 10 || n < 0)
{
printf("Invalid Input");
return 0;
}
printf("Enter Elements\n");
for(index = 0 ; index < n ; index++)
{
printf("Element %d : ", index + 1);
scanf("%d", &arr[index]);
}
merge_sort(arr, 0, n - 1);
printf("\nSorted Array\n");
for(index = 0 ; index < n ; index++)
{
printf("Element %d : %d\n", index + 1, arr[index]);
}
return 0;
}