divide and conquer program in c

Solutions on MaxInterview for divide and conquer program in c by the best coders in the world

showing results for - "divide and conquer program in c"
Cassie
15 Nov 2020
1#include<stdio.h>
2
3int arr[8]={1, 2, 3, 4, 5, 6, 7, 8};
4
5int main()
6{
7    int i;
8    merge_sort(arr, 0, 7);
9
10    printf("Sorted array:");
11
12    for(i = 0; i < 8; i++)
13        printf("%d", arr[i]);
14
15    return 0;
16}
17
18int merge_sort(int arr[],int low,int high)
19{
20    printf("\nmerge_sort initialization\n");
21
22    int mid;
23
24    if(low < high) 
25    {
26        mid = (low + high) / 2;
27
28        // Divide and Conquer
29        merge_sort(arr, low, mid); 
30        printf("\n merge_sort first\n");
31
32        merge_sort(arr, mid + 1, high); 
33        printf("\n merge_sort second\n");
34
35        // Combine
36        merge(arr, low, mid, high); 
37        printf("\nmerging\n");
38    }
39
40    return 0;
41}
42
43int merge(int arr[], int l, int m, int h)
44{
45    int arr1[10], arr2[10];
46    int n1, n2, i, j, k;
47    n1 = m - l + 1;
48    n2 = h - m;
49
50    for(i = 0; i < n1; i++)
51        arr1[i] = arr[l + i];
52
53    for(j = 0; j < n2; j++)
54        arr2[j] = arr[m + j + 1];
55
56    arr1[i] = 9999;
57    arr2[j] = 9999;
58
59    i = 0;
60    j = 0;
61
62    for(k = l; k <= h; k++)
63    {
64        if(arr1[i] <= arr2[j])
65            arr[k] = arr1[i++];
66        else
67            arr[k] = arr2[j++];
68    }
69
70    return 0;
71}
72