如何在数组中对大数字进行冒泡?

时间:2014-04-04 21:01:59

标签: java arrays sorting

我的问题是 -

已提供String,nums数组作为输入。每个String表示一个非负整数。整数可以非常大,因此已经存储为字符串。数组必须按字符串整数值的升序排序。 冒泡({" 999"" 723534"" 99"" 18456543876"" 54253445340001"&# 34; 98"" 112343",})

预期输出是 - {" 98"," 99"," 999"," 112343"," 723534&# 34;," 18456543876"" 54253445340001"}

实际输出是 - {" 99"," 98"," 999"," 112343"," 723534&# 34;," 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;
    }
}

2 个答案:

答案 0 :(得分:1)

问题在于,您要按照String的长度进行比较:

if (arr[i].length()>arr[j].length()) { //here's the problem!
    String temp=arr[i];
    arr[i]=arr[j];
    arr[j]=temp;
}

您最好的选择是将这些String转换为数字表示形式,例如long

long elem1 = Long.parseLong(arr[i]);
long elem2 = Long.parseLong(arr[j]);
if (elem1 > elem2) {
    String temp=arr[i];
    arr[i]=arr[j];
    arr[j]=temp;
}

如果数字真的很大,大于最大长值9223372036854775807,那么请改用BigInteger

BigInteger elem1 = new BigInteger(arr[i]);
BigInteger elem2 = new BigInteger(arr[j]);
if (elem1.compareTo(elem2) > 0) {
    String temp=arr[i];
    arr[i]=arr[j];
    arr[j]=temp;
}

答案 1 :(得分:1)

首先将元素长度缩短

if (arr[i].length()>arr[j].length()) { 
String temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}

现在问题是使用相同的长度元素。当结果为&gt;时,使用98和99 .use compareTo运算符交换1

如果j > j+1交换数字,例如"99".compareTo."98" =1

计算第一位数的差值,但如果第一位数字相同,则比较下一位数字并计算差值(左侧>&gt;右侧)

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;
   }
}