ALLInterview.com :: Home Page KalAajKal.com
 Advertise your Business Here     
Browse  |   Placement Papers  |   Company  |   Code Snippets  |   Certifications  |   Visa Questions
Post Question  |   Post Answer  |   My Panel  |   Search  |   Articles  |   Topics  |   ERRORS new
   Refer this Site  Refer This Site to Your Friends  Site Map  Bookmark this Site  Set it as your HomePage  Contact Us     Login  |  Sign Up                      
Do you have a collection of Interview Questions and interested to share with us!!
Please send that collection to along with your userid / name. ThanQ
Google
 
Categories >> Code-Snippets >> Programming-Code >> C-Code
 
 
 
Question
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. 
 Question Submitted By :: Maggy
I also faced this Question!!     Rank Answer Posted By  
 
Answer
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;

}
 
0
Ashish
 
View All Answers
 
 
 
 
 
   
Copyright Policy  |  Terms of Service  |  Help  |  Site Map 1  |  Articles  |  Site Map  |   Site Map  |  Contact Us interview questions urls   External Links 
   
Copyright © 2007  ALLInterview.com.  All Rights Reserved.

ALLInterview.com   ::  Forum9.com   ::  KalAajKal.com