Problem 49:(Round 2 Java Preparation)

49

Problem of the Day:
You want to sort words lexicographically without using inbuilt functions like Arrays.sort().


  • Input:{"zebra", "apple", "mango", "ball", "cat", "dog", "elephant", "fish", "ant", "bat"};



  • Output:ant apple ball bat cat dog elephant fish mango zebra


.snippet-thumbnail img { max-width: 50px; height: auto; object-fit: cover; }

Comments

  1. import java.util.Arrays;

    class Main {
    public static void main(String[] args) {
    String[] A = {"pant", "ants", "Dot", "Pot","Apple","Pots"};

    for (int i = 0; i < A.length - 1; i++) {
    for (int j = i + 1; j < A.length; j++) {
    if (isLexo(A[i], A[j]) > 0) {
    String temp = A[i];
    A[i] = A[j];
    A[j] = temp;
    }
    }
    }


    System.out.println("Sorted array: " + Arrays.toString(A));
    }

    public static int isLexo(String a, String b) {
    int len = Math.min(a.length(), b.length());

    for (int i = 0; i < len; i++) {
    if (a.charAt(i) < b.charAt(i)) {
    return -1;
    } else if (a.charAt(i) > b.charAt(i)) {
    return 1;
    }
    }

    if (a.length() < b.length()) return -1;
    if (a.length() > b.length()) return 1;
    return 0;
    }
    }

    ReplyDelete

Post a Comment

Popular posts from this blog

Strings

Arrays