In: Computer Science
Change the code to sort list of strings without using any pre-defined functions
Here is my code:
int n; String temp; Scanner in = new Scanner(System.in); System.out.print("Enter number of names you want to enter:"); n = in.nextInt(); String names[] = new String[n]; Scanner s1 = new Scanner(System.in); System.out.println("Enter all the names:"); for(int i = 0; i < n; i++){ names[i] = s1.nextLine(); } ***CHANGE THIS PART*** for (int i = 0; i < n; i++){ for (int j = i + 1; j < n; j++){ if (names[i].compareTo(names[j])>0) { temp = names[i]; names[i] = names[j]; names[j] = temp; } } } *** I WANT TO SORT WITHOUT USING ".compareto()" OR ANY OTHER PRE-DEFINED FUNCTION*** System.out.print("Names in Sorted Order:"); for (int i = 0; i < n - 1; i++){ System.out.print(names[i] + ","); } System.out.print(names[n - 1]);
Answer:-
Hello, I have modified the given program so as it can sort the array of Strings without using any predefined function. Please find it below.
Here I have written a user-defined function compareString which is used for comparing two strings. And from the main function, we are calling this compartString function for comparing the Strings of names array.
JAVA CODE:-
import java.util.Scanner;
class Solution
{
/* compareString function for comparing two
strings*/
static int compareString(String a,String b)
{
a=a.toUpperCase();
b=b.toUpperCase();
/*Loop for visiting each character
of Strings*/
for(int
i=0;i<a.length()&&i<b.length();i++)
{
/*Checking if
the character at index i in both strings are equal or not*/
if(a.charAt(i)==b.charAt(i))
{
}
/* If String a is greter than String b then it will return
1*/
else if(a.charAt(i)>b.charAt(i))
{
return 1;
}
/* If String a is lesser than String b then it will return
-1*/
else
{
return -1;
}
}
/*If both the Strings are equal then it will return
0.*/
return 0;
}
public static void main(String [] args)
{
int n;
String temp;
Scanner in = new Scanner(System.in);
System.out.print("Enter number of names you want to enter:");
n = in.nextInt();
String names[] = new String[n];
Scanner s1 = new Scanner(System.in);
System.out.println("Enter all the names:");
for(int i = 0; i < n; i++){
names[i] = s1.nextLine();
}
for (int i = 0; i < n; i++){
for (int j = i + 1; j < n; j++){
if (compareString(names[i],names[j])==1) {
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
System.out.print("Names in Sorted Order:");
for (int i = 0; i < n - 1; i++){
System.out.print(names[i] + ",");
}
System.out.print(names[n - 1]);
}
}
Screenshot of Code:-
Please refer to the screenshots of the code for properly understanding the indentation of the code.
Screenshot 1:
Screenshot 2:
OUTPUT:-
NOTE:- compareString is not any predefined function. We have defined this function in our code.
I hope it would help.
Thanks!