繁体   English   中英

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

[英]How can I bubble sort large numbers in an array?

我的问题是 -

提供了一个String,nums数组作为输入。 每个String表示一个非负整数。 整数可以非常大,因此已经存储为字符串。 数组必须按字符串整数值的升序排序。 冒泡({ “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;
    }
}

问题是你要比较你的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;
}

首先将元素长度缩短

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

现在问题是使用相同的长度元素, 例如98和99.当结果> 1时,使用compareTo操作符交换

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM