private static void sort_string(String [] str){
int i,j;
String temp;
for(i=0;i<str.length-2;i++){
for(j=str.length-1;j>i;j--){
if(str[j-1].compareTo(str[j])<0)
{
temp = str[j];
str[j] = str[j-1];
str[j-1] = temp;
}
}
}
}
我写的是冒泡排序,但是我将String类型转换成int类型是,排序是正确的。。。
这个是int的排序
private static void sort_int(int[] a){
int i,j;
int temp;
for(i=0;i<a.length-2;i++){
for(j=a.length-1;j>i;j--){
if(a[j]>a[j-1])
{
temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;
}
}
}
}
请输入一串数字,用","隔开:
13,98,28,34,5,7,3
string:13 28 3 34 5 7 98
int:98 34 28 13 7 5 3
这个是结果
我改了一下if(str[j-1].compareTo(str[j])0)
13,98,28,34,5,7,3
string:98 7 5 34 3 13 28
int:98 34 28 13 7 5 3
结果就这样了。。。就是按你的说13,是在28前面的啊
lz您的冒泡排序写的有问题:
应该如下:你试试
private static void sort_string(String[] str) {
int i, j;
String temp;
for (i = 0; i i; j--) {
if (str[j - 1].compareTo(str[j]) > 0) {
temp = str[j];
str[j] = str[j - 1];
str[j - 1] = temp;
}
}
}
}
LZ如果你是想排序数字的顺序话在比较的时候最好转化成数字类型那样就没问题了
在比较的时候:
if(str[j-1].compareTo(str[j])Integer.valueOf(str[j]))