java中数组的降序排序算法

ymdaylpp  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(301)

我试着编写一个程序,先对给定的字符串逐个排序,然后对所有字符串按降序排序。我设法按字符对字符串进行排序,但在按字符对所有已排序的字符串进行排序时遇到了问题。我尝试使用array.sort(),但它没有递减排序,它只对第一个输入排序,而不是已经排序的数组

package com.company;

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    static void sortString(String str)
    {
        char[] chArr = str.toCharArray();
        String SortString = "";
        for (int i = 0; i< chArr.length; i++)
        {
            for (int j = 0; j< chArr.length; j++)
            {
                if(chArr[i] > chArr[j])
                {
                    char temp = chArr[i];
                    chArr[i] = chArr[j];
                    chArr[j] = temp;
                }
            }
        }
        String[] SortedString = new String[5];

        for (int k = 0; k<chArr.length;k++)
        {
            SortString = SortString + chArr[k];
        }
        Arrays.sort(SortedString);
        for (int counter = 0; counter<5; counter++)
        {
            System.out.println(SortedString[counter]);
        }

    }
    public static void main(String[] args)
    {
        Scanner UserInput = new Scanner (System.in);

        String[] names = new String[5];

        for (int counter = 0; counter<5; counter++)
        {
            do
            {
                System.out.print("Input String #" + (counter+1) + ": ") ;
                names[counter] = UserInput.next().toLowerCase();
            }while(names[counter].length() > 25);

        }
        UserInput.close();
        Arrays.sort(names);
        for (int counter = 0; counter<5; counter++)
        {
            sortString(names[counter]);
        }

    }

}
dldeef67

dldeef671#

static String sortString(String str)
{
    char[] chArr = str.toCharArray();
    for (int i = 0; i< chArr.length; i++)
    {
        for (int j = 0; j< chArr.length; j++)
        {
            if(chArr[i] > chArr[j])
            {
                char temp = chArr[i];
                chArr[i] = chArr[j];
                chArr[j] = temp;
            }
        }
    }

    return new String(chArr);
}

public static void main(String[] args)
{
    Scanner UserInput = new Scanner (System.in);

    String[] names = new String[5];

    for (int counter = 0; counter<5; counter++)
    {
        do
        {
            System.out.print("Input String #" + (counter+1) + ": ") ;
            names[counter] = UserInput.next().toLowerCase();
        }while(names[counter].length() > 25);

    }
    UserInput.close();
    // Arrays.sort(names);   No point sorting here

    String[] strings = new String[5];
    for (int counter = 0; counter<5; counter++)
    {
        strings[counter] = sortString(names[counter]);
    }

     Arrays.sort(strings);

      // increasing order:
     for(String s : strings) {
         System.out.println(s);
     }

     // decreasing order:        
     for(int i = 4; i >= 0; i--) {
         System.out.println(strings[i]);
     }
}

相关问题