Given 5 strings as input, find the word which will appear in the middle if the strings are arranged in lexicographical order
middleWord("hello","how","are","you","today")="how"
middleWord("12","34","56","78","90")="56"
middleWord("hello","how","are","you","today")="how"
middleWord("12","34","56","78","90")="56"
public class MiddleWordOf5 {
static String testcase1 = "going";
static String testcase2 = "went";
static String testcase3 = "go";
static String testcase4 = "how";
static String testcase5 = "jam";
public static void main(String args[]){
MiddleWordOf5
testInstance= new MiddleWordOf5();
String
result = testInstance.middleWord(testcase1,testcase2,testcase3,testcase4,testcase5);
System.out.println("Result :
"+result);
}
//write your code
here
public String
middleWord(String word1,String word2,String word3,String word4, String word5){
String
largest="";
String
secondLargest="";
String
thirdLargest="";
if(word1.compareTo(word2)>=0
&& word1.compareTo(word3)>=0
)
{
largest=word1;
if(word2.compareTo(word3)>=0)
{
secondLargest=word2;
thirdLargest=word3;
}
else
{
secondLargest=word3;
thirdLargest=word2;
}
}
else if(word2.compareTo(word3)>=0
&& word2.compareTo(word1)>=0)
{
largest=word2;
if(word1.compareTo(word3)>=0)
{
secondLargest=word1;
thirdLargest=word3;
}
else
{
secondLargest=word3;
thirdLargest=word1;
}
}
else
{
largest=word3;
if(word1.compareTo(word2)>=0)
{
secondLargest=word1;
thirdLargest=word2;
}
else
{
secondLargest=word2;
thirdLargest=word1;
}
}
// now checking for
the word4
if(word4.compareTo(largest)
>=0)
{
thirdLargest=secondLargest;
secondLargest=largest;
largest=word4;
}
else if(word4.compareTo(secondLargest)
>=0)
{
thirdLargest=secondLargest;
secondLargest=word4;
}
else if(word4.compareTo(thirdLargest)
>=0)
{
thirdLargest=word4;
}
//now checking for
word5
if(word5.compareTo(largest)
>=0)
{
thirdLargest=secondLargest;
secondLargest=largest;
largest=word5;
}
else if(word5.compareTo(secondLargest)
>=0)
{
thirdLargest=secondLargest;
secondLargest=word5;
}
else if(word5.compareTo(thirdLargest)
>=0)
{
thirdLargest=word5;
}
return thirdLargest;
}
}
No comments:
Post a Comment