简体   繁体   中英

Sort strings in an array based on length

I have the below program for sorting Strings based on length. I want to print the shortest element first. I don't want to use Comparator or any API to do this. Where I am going wrong?

public class SortArrayElements {
    public static void main(String[] args) {
        String[] arr = new String[]{"Fan","dexter","abc","fruit","apple","banana"};
        String[] sortedArr = new String[arr.length];

        for(int i=0;i<sortedArr.length;i++)
        {           
            sortedArr[i] = compareArrayElements(arr);                       
        }

        System.out.println("The strings in the sorted order of length are: ");
        for(String sortedArray:sortedArr)
        {
            System.out.println(sortedArray);
        }
    }

    public static String compareArrayElements(String[] arr) {
        String temp = null;
        for(int i=0;i<arr.length-1;i++)
        {
            temp = new String();
            if(arr[i].length() > arr[i+1].length())
                temp = arr[i+1];
            else
                temp = arr[i];
        }
        return temp;
    }
}

Use bubble sort , but instead of comparing int s, just compare String lengths.

I won't write the code for you. You will have to do a little bit of research on this algorithm. Google is your best friend as a programmer.

Good luck.

If you really want to learn Java: use a Comparator. Any other way is bad Java code.

You can however rewrite the Comparator system if you want, it will teach you about proper code structuring.

For your actual code, here are some hints:

  • Using the proper algorithm is much more important than the Language you use to code. Good algorithms are always the same, no matter the language.

  • Do never do new in loops, unless you actually need to create new objects. The GC says "thanks".

  • Change the compareArrayElements function to accept a minimum size and have it return the smallest String with at least minimum size.

  • You could cut out those Strings that you have considered to be the smallest (set them to null), this will however modify the original array.

Implement bubbleSort() and swap() . My implementations mutate the original array, but you can modify them to make a copy if you want.

public class SortArrayElements {
    public static void main(String[] args) {
        String[] arr = new String[]{"Fan", "dexter", "abc", "fruit", "apple", "banana"};
        bubbleSort(arr);

        System.out.println("The strings in the sorted order of length are: ");
        for (String item : arr) {
            System.out.println(item);
        }

    }

    // Mutates the original array
    public static void bubbleSort(String[] arr) {
        boolean swapped = false;
        do {
            swapped = false;
            for (int i = 0; i < arr.length - 1; i += 1) {
                if (arr[i].length() > arr[i + 1].length()) {
                    swap(arr, i, i + 1);
                    swapped = true;
                }
            }
        } while (swapped);
    }

    // Mutates the original array
    public static void swap(String[] arr, int index0, int index1) {
        String temp = arr[index0];
        arr[index0] = arr[index1];
        arr[index1] = temp;
    }
}
//sort String array based on length 

public class FirstNonRepeatedString {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        System.out.println("Please Enter your String");
        String str = in.nextLine();
        String arrString[] = str.split("\\s"); 
        arrString = sortArray(arrString);
        System.out.println("Sort String ");
        for(String s:arrString){
            System.out.println(s);
        }
    }

    private static String[] sortArray(String[] arrString) {
        int length = arrString.length;
            String s;
            for (int i = 0; i < length ; i++) {
                s= new String();

              for(int j = 0; j < length; j++ ){
                  if(arrString[i].length()< arrString[j].length()){
                      s = arrString[i];
                      arrString[i] = arrString[j];
                      arrString[j] = s;
                  }
              }
            }

        return arrString;
    }
}

Okay, there is the code completely based on loops and on bubble sort. No sets are there as you wanted it. This is a pure loop program so you could understand the nested loops, plus it doesn't change the index or something of the string

      import java.util.*;

    class strings {
    public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    ArrayList<String> a = new ArrayList<String>(2);
    System.out.println("Start entering your words or sentences.");
    System.out.println("Type stop to stop.");
    String b;
    int c = 0, d;

    do {
        b = in.nextLine();
        b = b.trim();
        a.add(b);
        c++;
    }
    while (!b.equalsIgnoreCase("stop"));
    if (c > 1)
        a.remove(a.size() - 1);


    System.out.println("Choose the sort you want. Type the corresponding 
    number");
    System.out.println("1. Ascending");
    System.out.println("2. Descending");
    int sc=in.nextInt();
    switch(sc) {

        case 1: {
            int sag[] = new int[a.size()];

            for (int jk = 0; jk < a.size(); jk++) {
                b = a.get(jk);
                c = b.length();
                sag[jk] = c;
            }
            int temp;
            for (int i = 0; i < a.size() - 1; i++) {
                for (int j = 0; j < a.size() - 1; j++) {
                    if (sag[j] > sag[j + 1]) {
                        temp = sag[j + 1];
                        sag[j + 1] = sag[j];
                        sag[j] = temp;
                    }
                }
            }
            ArrayList saga = new ArrayList();
            for (int i = 0; i < sag.length; i++) {
                saga.add(sag[i]);

            }
            for (int i = 0; i < saga.size(); i++) {

                for (int j = i + 1; j < saga.size(); j++) {
                    if (saga.get(i).equals(saga.get(j))) {
                        saga.remove(j);
                        j--;
                    }
                }

            }


            for (int i = 0; i < saga.size(); i++) {
                for (int j = 0; j < a.size(); j++) {
                    String jl = a.get(j);
                    if (saga.get(i).equals(jl.length()))
                        System.out.println(jl);
                }
            }
            break;
        }
        case 2: {
            int sag[] = new int[a.size()];

            for (int jk = 0; jk < a.size(); jk++) {
                b = a.get(jk);
                c = b.length();
                sag[jk] = c;
            }
            int temp;
            for (int i = 0; i < a.size() - 1; i++) {
                for (int j = 0; j < a.size() - 1; j++) {
                    if (sag[j] < sag[j + 1]) {
                        temp = sag[j + 1];
                        sag[j + 1] = sag[j];
                        sag[j] = temp;
                    }
                }
            }
            ArrayList saga = new ArrayList();
            for (int i = 0; i < sag.length; i++) {
                saga.add(sag[i]);

            }
            for (int i = 0; i < saga.size(); i++) {

                for (int j = i + 1; j < saga.size(); j++) {
                    if (saga.get(i).equals(saga.get(j))) {
                        saga.remove(j);
                        j--;
                    }
                }

            }


            for (int i = 0; i < saga.size(); i++) {
                for (int j = 0; j < a.size(); j++) {
                    String jl = a.get(j);
                    if (saga.get(i).equals(jl.length()))
                        System.out.println(jl);
                }
            }
            break;
        }
    }


}
}

Let's take a following array of String inputArray = ["abc","","aaa","a","zz"]

we can use Comparator for sorting the given string array to sort it based on length with the following code:

String[] sortByLength(String[] inputArray) {
        Arrays.sort(inputArray, new Comparator<String>(){
            public int compare(String s1, String s2){
                return s1.length() - s2.length();
            }
        });
        return inputArray;
    }

For instance, the following:

ArrayList<String> str = new ArrayList<>(
Arrays.asList(
"Long", "Short", "VeryLong", "S")
);

By lambda:

str.sort((String s1, String s2) -> s1.length() - s2.length());

By static Collections.sort

 import static java.util.Collections.sort;
    sort(str, new Comparator<String>{
       @Override
         public int compare(String s1, String s2) {
           return s1.lenght() - s2.lenght()
}
});

Both options are implemented by default sort method from List interface

We can simply use below code.

 String[] sortByLength(String[] inputArray) {
        Arrays.sort(inputArray, Comparator.comparingInt(String::length));
        return inputArray;
    }
import java.util.*;
public class SortStringBasedOnTheirLength {

    public static void main(String[] args) {

    Scanner sc=new Scanner(System.in);

      System.out.println("Enter String:");

      String str=sc.nextLine();

      String[] str1=str.split("\\s");

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

      for(int i=0;i<str1.length;i++)
      {
         System.out.print(str1[i]+" "); 
      }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM