Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- int na,nb;
- void mergeSort(int c[], int low, int mid, int high);
- void input(int a[],int b[])
- {
- int i;
- printf("Enter the limit of A: ");
- scanf("%d",&na);
- printf("Enter the limit of B: ");
- scanf("%d", &nb);
- printf("Enter %d elements of A:-\n", na);
- for(i=0; i<na; i++)
- scanf("%d", &a[i]);
- printf("Enter %d elements of B:-\n", nb);
- for(i=0; i<nb; i++)
- scanf("%d", &b[i]);
- }
- void merge(int a[], int b[], int c[])
- {
- int i,j = 0;
- for(i=0; i<na; i++)
- c[i] = a[i];
- for (i; i<(na+nb); i++)
- c[i] = b[j++];
- printf("The unsorted array is:\t");
- for(i=0; i<(na+nb); i++)
- printf("%d ", c[i]);
- }
- void partition(int c[], int low, int high)
- {
- int mid;
- if(low < high)
- {
- mid = (low + high)/2;
- partition(c, low, mid);
- partition(c,(mid+1), high);
- mergeSort(c, low, mid, high);
- }
- }
- void mergeSort(int c[], int low, int mid, int high)
- {
- int i = low, l = low, m = mid + 1, k, temp[200];
- while ((l <= mid) && (m <= high))
- {
- if(c[l] <= c[m])
- {
- temp[i] = c[l];
- l++;
- }
- else
- {
- temp[i] = c[m];
- m++;
- }
- i++;
- }
- if( l > mid)
- {
- for (k = m; k <= high; k++)
- {
- temp[i] = c[k];
- i++;
- }
- }
- else
- {
- for(k = l;k <= mid; k++)
- {
- temp[i] = c[k];
- i++;
- }
- }
- for (k = low; k <= high; k++)
- c[k] = temp[k];
- }
- void display(int c[])
- {
- int i;
- printf("\nThe sorted array is:\t");
- for(i = 0; i < (na+nb); i++)
- printf("%d ", c[i]);
- }
- void search(int c[])
- {
- int left = 0, right = (na + nb - 1), mid, key, found = 0;
- printf("\nEnter the element you want to find: ");
- scanf("%d",&key);
- while(left <= right)
- {
- mid = (left + right)/2;
- if(key == c[mid])
- {
- found = 1;
- break;
- }
- else if(key < c[mid])
- right = mid - 1;
- else
- left = mid + 1;
- }
- if (found == 1)
- printf("\n%d is found! It is at position %d.",key, mid);
- else
- printf("\n%d is not found in the array!", key);
- }
- int main()
- {
- int a[100],b[200],c[200];
- input(a, b);
- merge(a, b, c);
- partition(c, 0, (na+nb-1));
- display(c);
- search(c);
- }
- //Output
- //Enter the limit of A: 3
- //Enter the limit of B: 3
- //Enter 3 elements of A:-
- //3
- //2
- //1
- //Enter 3 elements of B:-
- //6
- //5
- //4
- //The unsorted array is: 3 2 1 6 5 4
- //The sorted array is: 1 2 3 4 5 6
- //Enter the element you want to find: 4
- //
- //4 is found! It is at position 3.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement