簡體   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