PTA_字符串排序_JAVA

本题要求编写程序,读入5个字符串,按由小到大的顺序输出。

输入格式:

输入为由空格分隔的5个非空字符串,每个字符串不包括空格、制表符、换行符等空白字符,长度小于80。

输出格式:

按照以下格式输出排序后的结果:

After sorted:
每行一个字符串

输入样例:

red yellow blue green white

输出样例:

After sorted:
blue
green
red
white
yellow


import java.util.*;
public class Main {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		int i,n;
		n = 5;
		String temp;
		String[] list = new String[5];
		Main work = new Main();
		for(i = 0;i<5;i++)
		{
			list[i] = new String();
		}
		temp = input.nextLine();
		for(i=0;i<4;i++)
		{
			list[i] = temp.substring(0, temp.indexOf(' '));
			temp = temp.substring(temp.indexOf(' ')+1);
		}
		list[i] = temp;
		work.order(list,n );
		System.out.println("After sorted:");
		for(i = 0;i<n;i++)
		{
			System.out.println(list[i]);
		}
		input.close();
	}
	public void order(String[] list,int n)
	{
		int i,k;
		String temp;
		for(i = 0;i<n;i++)
		{
			for(k=n-1;k>0;k--)
			{
				if(list[k-1].compareTo(list[k])>0)
				{
					temp = list[k-1];
					list[k-1] = list[k];
					list[k] = temp;
				}
			}
		}
	}

}

PTA_字符串排序_JAVA