Skip to content
Advertisement

Sorting empty and word array in java

I want to write a code which can sort char array element. But the problem is where i want to sort ‘a’ before ‘aa’ element and I don’t know how to write this part. It always sort ‘aa’ before ‘a’. At first it get inputs from user and if we write ‘0’ it will print sorted array.

    import java.util.Scanner;

public class First {
    public static void main(String[] args) {
        int i, num = 0;
        char[][] arr = new char[1000][1000];
        char[] index = new char[1000];
        Scanner myObj = new Scanner(System.in);
        for(i = 0; i < 1000; i++){
            arr[i] = myObj.next().toCharArray();
            if(arr[i][0] == '0'){
                break;
            }
            else{
                num++;
            }
            for(int j = 0; j < i; j++){
                if(arr[i][0] < arr[j][0]){
                    index = arr[i];
                    arr[i] = arr[j];
                    arr[j] = index;
                    j = 0;
                }
            }
        }
        for(i = 0; i < num; i++){
            System.out.println(arr[i]);
        }
    }
}

Advertisement

Answer

You have to consider that 'aa' is not a char, instead 'a' is a char. If you want to sort strings the code is nearly okay.

Here an example:

import java.util.Scanner;

public class First {

public static void main(String[] args) {
    int num = 0;
    String[] arr = new String[1000];
    String index = "";
    Scanner myObj = new Scanner(System.in);
    for(int i = 0; i < 1000; i++){
        arr[i] = myObj.nextLine();
        if(arr[i].equals("0")){
            break;
        }
        else{
            num++;
        }
        for(int j = 0; j < i; j++){
            if(arr[i].compareTo(arr[j]) < 0){
                index = arr[i];
                arr[i] = arr[j];
                arr[j] = index;
                j = 0;
            }
        }
    }

    System.out.print("[ ");
    for(int i = 0; i < num; i++){
        System.out.print(arr[i] + " ");
    }
    System.out.println("]");
   }
}

Input:

aaaaaaaa
aaaaaaa
aaaaaa
aaaaa
aaaa
aaa
aa
a
0

Expected Output:

[ a aa aaa aaaa aaaaa aaaaaa aaaaaaa aaaaaaaa ]
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement