Monday, October 1, 2012

Merging of two sorted arrays

 

Given two sorted arrays A & B where size of A is m & size of B is m+n .  B contains only n number of elements & m empty positions. Sorting should not take any extra memory.

#include<stdio.h>
main()
{
int A[]={1,3,7,10};
int B[7]={2,4,11};
int size_A;
int size_B;
int i;
size_A=sizeof(A)/sizeof(int);
size_B=sizeof(B)/sizeof(int);
size_A--;
size_B--;
int s=size_B;
int B_Elements= (size_B - size_A);
B_Elements--;

while((size_A >=0) && (B_Elements >=0))
{
if( (A[size_A] ) >= (B[B_Elements])){
        B[size_B]=A[size_A];

        printf("\n%d > = %d",A[size_A ] , B[B_Elements ]);
        size_A--;
        size_B--;
}
else
{
printf("\n%d < = %d",A[size_A ] , B[B_Elements ]);
B[size_B] = B[B_Elements];
size_B--;
B_Elements--;
}
}

if ( size_A >=0 ){
    while ( size_A >= 0 ){
B[size_B] = A[size_A];
size_A--;
size_B--;
    }
}
else if ( B_Elements >=0 ) {
    while (B_Elements >=0){
B[size_B] = B[size_B];
    B_Elements--;
    size_B--;
    }
}
else {
printf("Merging done");
}
printf("\n");
for(i=0;i<=s;i++)
printf("%d  ",B[i]);
}

Permutation of a given string


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void swap(char *x , char *y)
{
    char temp;
    temp=*x;
    *x=*y;
    *y=temp;
}
void do_permute(char *a, int start , int size)
{
    int itr;
    if ( start == size ){
        printf("%s\n",a);
    }
    else{
        for(itr=start;itr<size;itr++)
        {
            swap((a+start),(a+itr));
            do_permute(a,start+1,size);
            swap((a+start),(a+itr));
        }
    }
}
main()
{
    printf("PERMUTATION\n");
    char a[100];
    int size;
    scanf("%s",a);
    size=strlen(a);
    do_permute(a,0,size);
}