Skip to main content

ProwessApps

Learn · Practice · Excel

Create a String array that stores name of students and then perform namewise sorting on that array to sort the list of students.

Java Code Example — String Programs

ADVERTISEMENT

Create a String array that stores name of students and then perform namewise sorting on that array to sort the list of students.

Objective

Write a Java program to sort an array of student names alphabetically.

Algorithm / Approach

  1. Create a method sort(String[] x) that accepts an array of strings.
  2. Use nested loops (like Bubble Sort) to compare elements.
  3. Instead of using > (which only works for numbers), use the compareTo() method: if(x[i].compareTo(x[j]) > 0).
  4. If the condition is true, swap the strings using a temporary variable.
  5. Print the sorted array.
Test.java
class Test {
 void sort(String[] x) {
  int n = x.length;
  String temp;
  for(int i = 0; i < n; i++) {
   for(int j = i + 1; j < n; j++) {
    if(x[i].compareTo(x[j])>0) {
     temp = x[i];
     x[i] = x[j];
     x[j] = temp;
    }
   }
  }
  System.out.println("Sorted Order:");
  for (int i = 0; i < n-1; i++) {
   System.out.print(x[i] + "   ");
  }
 }
 public static void main(String[] a)
 {
  String[] x = {"Daneyal","Arif",
  "Faiz","Ayan","Alok"};
  Test t = new Test();
  t.sort(x);
 }
}

Expected Output

Sorted Order:
Alok   Arif   Ayan   Daneyal   Faiz

Explanation of the Program

  • Sorting strings alphabetically requires comparing their dictionary (lexicographical) order.
  • The compareTo() method compares two strings character by character based on their ASCII values. If the first string comes alphabetically *after* the second string, it returns a positive number (greater than 0).
  • By combining this string comparison method with standard sorting algorithms like Bubble Sort, we can easily alphabetize any list of names.

Complexity

Time Complexity O(n2 * m) - Where n is the number of strings and m is the length of the strings being compared.
Space Complexity O(1)

Common Mistakes

  • Attempting to use the standard &gt; or &lt; operators on strings, which will result in a syntax error.
ADVERTISEMENT