Search
 
SCRIPT & CODE EXAMPLE
 

C

divide and conquer program in c

#include<stdio.h>

int arr[8]={1, 2, 3, 4, 5, 6, 7, 8};

int main()
{
    int i;
    merge_sort(arr, 0, 7);

    printf("Sorted array:");

    for(i = 0; i < 8; i++)
        printf("%d", arr[i]);

    return 0;
}

int merge_sort(int arr[],int low,int high)
{
    printf("
merge_sort initialization
");

    int mid;

    if(low < high) 
    {
        mid = (low + high) / 2;

        // Divide and Conquer
        merge_sort(arr, low, mid); 
        printf("
 merge_sort first
");

        merge_sort(arr, mid + 1, high); 
        printf("
 merge_sort second
");

        // Combine
        merge(arr, low, mid, high); 
        printf("
merging
");
    }

    return 0;
}

int merge(int arr[], int l, int m, int h)
{
    int arr1[10], arr2[10];
    int n1, n2, i, j, k;
    n1 = m - l + 1;
    n2 = h - m;

    for(i = 0; i < n1; i++)
        arr1[i] = arr[l + i];

    for(j = 0; j < n2; j++)
        arr2[j] = arr[m + j + 1];

    arr1[i] = 9999;
    arr2[j] = 9999;

    i = 0;
    j = 0;

    for(k = l; k <= h; k++)
    {
        if(arr1[i] <= arr2[j])
            arr[k] = arr1[i++];
        else
            arr[k] = arr2[j++];
    }

    return 0;
}
Comment

PREVIOUS NEXT
Code Example
C :: copy string c 
C :: svg not loading in chrome 
C :: find length of int number in c 
C :: %d in c 
C :: to find greatest of 4 numbers in c 
C :: why do we need return 0 in c? 
C :: c program to find minimum of 4 numbers using conditional operator in c 
C :: insertion sort c 
C :: install tweaks ubuntu 
C :: c modify char array 
C :: strcmp c 
C :: read a document in c getting name from console 
C :: make a function makefile 
C :: multiplication table in c 
C :: print a part of string c 
C :: bd number regex 
C :: bootstrap 4 forms 
C :: how to use malloc in c 
C :: program to find the average of n numbers using arrays. 
C :: convert string to int c 
C :: calculate median 
C :: set all pins as output for loop 
C :: esp8266 wifi.config does not work 
C :: print 100 times c 
C :: working outside of application context 
C :: size of operator in c language 
C :: how to declare a struct in c 
C :: pipe system call 
C :: Highest integer among the four inputs in c 
C :: leer string en c 
ADD CONTENT
Topic
Content
Source link
Name
5+4 =