Given an array of integers, for each index i, swap the value at i with the first value smaller than a[ i ] that comes after index i. Write a C Program?
For example : If given array is a[]={3,7,4,9,10,2,1}
Output -- a[]={2,4,3,7,9,1,10}
Algorithm:
1) Start from the first element of the array and compare it with rest of the elements.
2) If a element is found which is smaller,swap it and break the execution.
3) Continue with the second element and so on.(until u reach the end of the array)
This solution is O(n^2).
Program:
#include<stdio.h>
#include<conio.h>
void fun(int a[],int,int);void main()
{
int a[]={3,7,4,9,10,2,1};
int len=sizeof(a)/sizeof(int);
int i;
clrscr();
fun(a,0,len);
getch();
}
void fun(int a[],int n,int len)
{
int temp,i;
if(n<len)
{
for(i=n+1;i<len;i++)
if(a[n]>a[i])
{
temp=a[i];
a[i]=a[n];
a[n]=temp;
break;
}
fun(a,n+1,len);
}
else
{
for(i=0;i<len;i++)
printf("%d\t",a[i]);
}
}
For example : If given array is a[]={3,7,4,9,10,2,1}
Output -- a[]={2,4,3,7,9,1,10}
Algorithm:
1) Start from the first element of the array and compare it with rest of the elements.
2) If a element is found which is smaller,swap it and break the execution.
3) Continue with the second element and so on.(until u reach the end of the array)
This solution is O(n^2).
Program:
#include<stdio.h>
#include<conio.h>
void fun(int a[],int,int);void main()
{
int a[]={3,7,4,9,10,2,1};
int len=sizeof(a)/sizeof(int);
int i;
clrscr();
fun(a,0,len);
getch();
}
void fun(int a[],int n,int len)
{
int temp,i;
if(n<len)
{
for(i=n+1;i<len;i++)
if(a[n]>a[i])
{
temp=a[i];
a[i]=a[n];
a[n]=temp;
break;
}
fun(a,n+1,len);
}
else
{
for(i=0;i<len;i++)
printf("%d\t",a[i]);
}
}
No comments:
Post a Comment