版权声明:文章都是原创,转载请注明~~~~ https://blog.csdn.net/SourDumplings/article/details/88685185
多类型排序
我们现在有一些数据,是整数和字符串混杂的。现在需要你将他们分开,并且分别进行排序。
请你利用泛型实现一个数组类,并且实现排序函数,使得其既可以对Integer类型进行排序,又可以对String类型进行排序。然后利用你实现的这个类完成上面的任务。
输入格式:
一行,一个数字n,表示元素的个数。
n行,每行一个字符串整数,也可以是其他字符串。
输出格式:
n行,前面一部分为输入的整数字符串按从小到大排序输出,后面一部分为非整数字符串按照字典序从小到大输出。
输入样例:
5
12
ab
bd
23
t
输出样例:
12
23
ab
bd
t
Java:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int N = Integer.parseInt(sc.nextLine());
int ns = 0, nn = 0;
String[] s = new String[N];
Integer[] in = new Integer[N];
for (int i = 0; i != N; ++i)
{
String line = sc.nextLine();
boolean isNum = true;
int l = line.length();
for (int j = 0; j != l; ++j)
{
if (!Character.isDigit(line.charAt(j)))
{
isNum = false;
break;
}
}
if (isNum)
{
in[nn++] = Integer.parseInt(line);
}
else
{
s[ns++] = line;
}
}
(new SortInteger()).doSort(in, nn);
(new SortString()).doSort(s, ns);
for (int i = 0; i != nn; ++i)
System.out.println(in[i]);
for (int i = 0; i != ns; ++i)
System.out.println(s[i]);
sc.close();
}
}
abstract class Sort<T>
{
public void doSort(T[] A, int n)
{
for (int i = 1; i != n; ++i)
{
int j;
T x = A[i];
for (j = i; j >= 1 && cmp(x, A[j-1]); --j)
A[j] = A[j - 1];
A[j] = x;
}
}
public abstract boolean cmp(T a, T b);
}
class SortString extends Sort<String>
{
public boolean cmp(String a, String b)
{
return a.compareTo(b) < 0;
}
}
class SortInteger extends Sort<Integer>
{
public boolean cmp(Integer a, Integer b)
{
return a < b;
}
}