Minggu, 10 Desember 2017

Merge Sort Array With Recursion

 Problem:

Write and test a merge function that uses a recursive algorithm to merge
two sorted arrays of integers. Neither list contains duplicates, and the
resulting list should not contain duplicates either.  Hint : You may want to
call a helper function from merge.

Answer:

#include<stdio.h>

int arrA[100],arrB[100],arrC[100],arrD[100];

int main() {
int i,j;
int nA,nB,nC;

printf("Masukan Panjang Array A = "); scanf("%d", &nA);
printf("Masukan Isi Array A = "); for(i=0;i<nA;i++) {
scanf("%d", &arrA[i]);
}
printf("Masukan Panjang Array B = "); scanf("%d", &nB);
printf("Masukan Isi Array B = "); for(i=0;i<nB;i++) {
scanf("%d", &arrB[i]);
}
nC=(nA+nB);
merge(0,0,nA,nB);
sort(nC);
no_dupe(0,1,0,nC);
for(i=0;i<nC;i++) {
if(arrD[i]==0) {
break;
}
printf("%d ", arrD[i]);
}
printf("\n");
}

int merge(int i, int j, int nA, int nB) {
if(i<nA) {
arrC[i]=arrA[i];
merge(i+1,j,nA,nB);
}
if(i>=nA) {
if(j==nB) {
return;
}
else {
arrC[i]=arrB[j];
merge(i+1,j+1,nA,nB);
}
}
}

int sort(int nC) {
int i,temp;
if(nC==1){
return;
}
else {
for(i=0;i<nC-1;i++){
if(arrC[i]>arrC[i+1]){
temp=arrC[i];
arrC[i]=arrC[i+1];
arrC[i+1]=temp;
}
}
sort(nC-1);
}
}

int no_dupe(int i, int j, int k, int nC) {
if(nC==0) {
return;
}
else {
if(arrC[i]!=arrC[j]) {
arrD[k]=arrC[i];
no_dupe(j,j+1,k+1,nC-1);
}
else {
no_dupe(i,j+1,k,nC-1);
}
}
}
Share:

0 komentar:

Posting Komentar

Allimdev.tk

Diberdayakan oleh Blogger.

Labels