我的问题是-
已提供字符串数组 nums 作为输入。每个字符串代表一个非负整数。整数可能非常大,因此已存储为字符串。该数组必须按字符串整数值的升序排序。 bubbleSort({"999","723534","99","18456543876","54253445340001","98","112343",})
预期输出为-{"98","99","999","112343","723534","18456543876","54253445340001"}
实际输出为-{"99","98","999","112343","723534","18456543876","54253445340001"}
我不知道如何比较相同数字的大数。
public class BubbleSortLargeNums {
static String[] testcase1 = {"999","723534","99","18456543876","54253445340001","98","112343",};
//static String[] testcase1 = {"1"};
public static void main(String args[]){
BubbleSortLargeNums testInstance = new BubbleSortLargeNums();
String[] result = testInstance.bubbleSort(testcase1);
System.out.print("{");
for (int i=0;i<result.length;i++){
if (i>0)
System.out.print(",");
System.out.print('"'+result[i]+'"');
}
System.out.println("}");
}
//write your code here
public String[] bubbleSort(String[] arr){
int j=0;
int prevI=0;
for(int i=0;i<arr.length-1;i++){
j++;
if(j<arr.length){
i=prevI;
}
else{
j=i+1;
}
if(arr[i].length()>arr[j].length()){
String temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
prevI=i;
}
return arr;
}
}
最佳答案
首先缩短元素的长度
if (arr[i].length()>arr[j].length()) {
String temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
现在问题将出在相同长度的元素例如98 和 99。当结果 > 1 时使用 compareTo
运算符交换
if j > j+1
交换数字,例如"99".compareTo."98"=1
计算第一位数字的差异,但如果第一位数字相同,则比较下一位数字并计算差异(左--->右)
if(str[j].length() == (str[j+1]).length()){
if ( str[j].compareTo(str[j+1])>0 ){
String temp = str[j];
str[j] = str[j+1];
str[j+1] = temp;
}
}
关于java - 如何对数组中的大量数字进行冒泡排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22872946/