Given an array of characters which form a sentence of
words, give an efficient algorithm to reverse the order of
the words (not characters) in it.

Answer Posted / ashish

this works in O(n) as first reverse all the sentence....then
reverse each word....


#include<iostream.h>
#include<conio.h>
#include<string.h>

char a[50];

void wrd_reverse()
{
void str_rev(int start_index,int len);
int t=strlen(a);
str_rev(0,t);
int i=0;int st_indx=0;int count=0;
int size;
while(a[i]!='\0')
{
if(a[i]!=' ')
count++;
else
{

size=count;
str_rev(st_indx,size);
count=0;
st_indx=i+1;
}
i++;
}
size=count;
str_rev(st_indx,size);

}

void str_rev(int start_index,int len)
{
int sft=start_index;
int lenm=len/2;
len--;
for(int i=0;i<lenm;i++)
{
a[sft+i]=a[sft+i]+a[(sft+len)-i];
a[(sft+len)-i]=a[sft+i]-a[(sft+len)-i];
a[sft+i]=a[sft+i]-a[(sft+len)-i];
}
}

int main(){
cin.getline(a,40);
void wrd_reverse();
wrd_reverse();
cout.write(a,40);
return 0;

}

Is This Answer Correct ?    1 Yes 2 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Design an implement of the inputs functions for event mode

2957


why do you use macros? Explain a situation where you had to incorporate macros in your proc report? use a simple instream data example with code ?

2258


What is full form of PEPSI

1864


how to test pierrot divisor

2255


Sir... please give some important coding questions asked by product companies..

1793






write a simple calculator c program to perform addition, subtraction, mul and div.

3143


What is the difference between proc means and proc tabulate ? explain with a simple example when you have to use means or tabulate?

3707


Can you send Code for Run Length Encoding Of BMP Image in C Language in linux(i.e Compression and Decompression) ?

3844


how to programme using switch statements and fuctions, a programme that will output two even numbers, two odd numbers and two prime numbers of the users chioce.

2136


Set up procedure for generating a wire frame display of a polyhedron with the hidden edges of the object drawn with dashed lines

3026


Given a spherical surface, write bump-mapping procedure to generate the bumpy surface of an orange

2857


What is data _null_? ,Explain with code when u need to use it in data step programming ?

2820


Hi, i have a project that the teacher want a pyramid of numbers in C# or java...when we click a button...the pyramid should be generated in a listbox/or JtextArea...and the pyramid should have the folowing form: 1 232 34543 4567654 567898765 67890109876 7890123210987 890123454321098 90123456765432109 0123456789876543210 Plz help with codes...didn't find anything on the net.

2681


Develop a routine to reflect an object about an arbitrarily selected plane

2992


How to palindrom string in c language?

8835