Problem : Given an sequence of N Elements x1,x2,x3 ,........, Generate a permutation of sequence such that : x1<=x2<=x3<=x4 ,...... .
Sol : Start with single element and from second element on wards insert i Th element in proper position in sorted sequence .
Running Time : In Worst Case : O(N^2) , Where N is number of elements in sequence
Source Code In C :
#include <iostream>
using namespace std;
int main()
{
char arr[] = {'N','I','T','E','N','D','R','A','B','H','O','S','L','E'};
int sz = sizeof(arr)/sizeof(char);
for(int i = 1;i<sz;++i)
{
int j = i;
while(j>=0 && arr[j] < arr[j-1])
{
char temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
--j;
}
}
for(int i = 0;i<sz;++i)
{
cout<<"\n"<<arr[i];
}
return 0;
}
Sol : Start with single element and from second element on wards insert i Th element in proper position in sorted sequence .
Running Time : In Worst Case : O(N^2) , Where N is number of elements in sequence
Source Code In C :
#include <iostream>
using namespace std;
int main()
{
char arr[] = {'N','I','T','E','N','D','R','A','B','H','O','S','L','E'};
int sz = sizeof(arr)/sizeof(char);
for(int i = 1;i<sz;++i)
{
int j = i;
while(j>=0 && arr[j] < arr[j-1])
{
char temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
--j;
}
}
for(int i = 0;i<sz;++i)
{
cout<<"\n"<<arr[i];
}
return 0;
}
No comments :
Post a Comment