如何在没有字符串或数组的情况下按升序对整数数字进行排序?

时间:2015-11-28 12:19:23

标签: java sorting modulo

我正在尝试按升序对任意长度的整数进行排序,而不使用字符串,数组或递归。

示例:

int number = 4214;

while (number > 0) {
    IO.println(number % 10);
    number = number / 10;
}

我已经想出如何用模数除法得到整数的每个数字:

IO

但我不知道如何在没有数组的情况下订购数字。

不要担心@model dynamic @using (Html.BeginForm()) { @Html.Hidden("ModelType", Model.GetType()) @Html.EditorForModel() <input type="submit" value="OK" /> } 课程;这是我们教授给我们的一个习惯课。

10 个答案:

答案 0 :(得分:9)

它的4行,基于你的while循环的for循环变体,带有一点java 8 spice:

int number = 4214;

List<Integer> numbers = new LinkedList<>(); // a LinkedList is not backed by an array
for (int i = number; i > 0; i /= 10)
    numbers.add(i % 10);
numbers.stream().sorted().forEach(System.out::println); // or for you forEach(IO::println)

答案 1 :(得分:6)

实际上这是一个非常简单的算法,只使用整数

int number = 4214173;
int sorted = 0;
int digits = 10;
int sortedDigits = 1;
boolean first = true;

while (number > 0) {
    int digit = number % 10;

    if (!first) {

        int tmp = sorted;
        int toDivide = 1;
        for (int i = 0; i < sortedDigits; i++) {
            int tmpDigit = tmp % 10;
            if (digit >= tmpDigit) {
                sorted = sorted/toDivide*toDivide*10 + digit*toDivide + sorted % toDivide;
                break;
            } else if (i == sortedDigits-1) {
                sorted = digit * digits + sorted;
            }
            tmp /= 10;
            toDivide *= 10;
        }
        digits *= 10;
        sortedDigits += 1;
    } else {
        sorted = digit;
    }

    first = false;
    number = number / 10;
}
System.out.println(sorted);

它将打印出1123447。 这个想法很简单:

  1. 您获取要排序的数字的当前数字(让我们称之为N)
  2. 您浏览已排序号码中的所有数字(让我们称之为S)
  3. 如果S中的当前数字小于N中的当前数字,则只需将数字插入S中的当前位置。否则,您只需转到S中的下一位数。
  4. 该算法版本可以在desc命令的asc中进行排序,你只需要改变条件。

    另外,我建议你看一下所谓的Radix Sort,解决方案here从基数排序中获取一些想法,我认为基数排序是该解决方案的一般情况。

答案 2 :(得分:3)

我假设你被允许使用哈希。

public static void sortDigits(int x) {
    Map<Integer, Integer> digitCounts = new HashMap<>();

    while (x > 0) {
        int digit = x % 10;
        Integer currentCount = digitCounts.get(digit);
        if (currentCount == null) {
            currentCount = 0;
        }
        digitCounts.put(x % 10, currentCount + 1);
        x = x / 10;
    }

    for (int i = 0; i < 10; i++) {
        Integer count = digitCounts.get(i);
        if (count == null) {
            continue;
        }
        for (int j = 0; j < digitCounts.get(i); j++) {
            System.out.print(i);
        }
    }
}

答案 3 :(得分:2)

如何在不使用数组,字符串或排序API的情况下对数字进行排序?好吧,您可以按照以下简单步骤对数字进行排序(如果读取的内容太多,请参阅下面的调试输出以了解排序是如何完成的):

  1. 使用(数字=数字%10)
  2. 获取数字的最后一位数字
  3. 除以最后一位数后的数字(数字/ = 10)
  4. 循环显示数字的数字(没有数字)并检查数字是否最小
  5. 如果找到新的较小数字,则替换数字=最小数字并继续查看结束
  6. 在循环结束时,您找到了最小的数字,存储它(store =(store * 10)+ digit
  7. 现在你知道这是最小的数字,从数字中删除这个数字,并继续将上述步骤应用于剩余数字,每次找到一个较小的数字,然后将其添加到商店并从数字中删除数字(如果数字重复在数量上,然后将它们全部删除并添加到商店)
  8. 我在main方法和一个函数中提供了两个while循环的代码。该函数什么都不做,但是,构建一个新的整数,不包括传递给的数字,例如我传递函数451567和1,函数返回45567(以任何顺序,无关紧要)。如果此函数通过了451567和5,则它会在数字中找到5位数并将它们添加到存储并返回没有5位数的数字(这样可以避免额外处理)。

    调试,了解它如何对整数进行排序:

    最后一位是:数字7:451567
    子块是45156
    子箱是4515
    子箱是451
    子箱是45
    子箱是4
    451567中的数字是1 商店是:1
    从451567中删除1 减少的数量是:76554
    最后一位是:数字4:76554
    子箱是7655
    Subchunk是765
    子箱是76
    Subchunk是7
    76554中的数字是4
    商店是:14
    从76554中删除4 减少的数量是:5567
    最后一位是:数字7:5567
    子箱是556
    子箱是55
    子箱是5
    5567中的数字是5 商店是:145
    从5567中删除5 发现重复的最小数字5。商店是:145
    重复的最小数字5添加到商店。更新的商店是:1455

    减少的数量是:76
    最后一位是:数字6:76
    Subchunk是7
    76中的数字是6 商店是:14556
    从76中删除6 减少的数量是:7
    最后一位是:7的数字:7
    7中的数字是7 商店是:145567
    从7中删除7 减少的数量是:0
    451567的升序为145567

    示例代码如下:

    //stores our sorted number
         static int store = 0; 
    
         public static void main(String []args){
            int number = 451567; 
            int original = number; 
    
            while (number > 0) {
                //digit by digit - get last most digit
                int digit = number % 10;
    
                System.out.println("Last digit is : " + digit + " of number : " + number); 
    
                //get the whole number minus the last most digit 
                int temp = number / 10; 
    
                //loop through number minus the last digit to compare
                while(temp > 0) {
                    System.out.println("Subchunk is " + temp); 
                    //get the last digit of this sub-number
                    int t = temp % 10; 
    
                    //compare and find the lowest
                    //for sorting descending change condition to t > digit
                    if(t < digit)   
                        digit = t; 
    
                    //divide the number and keep loop until the smallest is found
                    temp = temp / 10;
                }
                System.out.println("Smalled digit in " + number  + " is " + digit); 
    
                //add the smallest digit to store 
                store = (store * 10) + digit; 
    
                System.out.println("Store is : " + store); 
    
                //we found the smallest digit, we will remove that from number and find the 
                //next smallest digit and keep doing this until we find all the smallest 
                //digit in sub chunks of number, and keep adding the smallest digits to 
                //store
                number = getReducedNumber(number, digit); 
            }
            System.out.println("Ascending order of " + original + " is " + store); 
         }
    
    
         /*
         * A simple method that constructs a new number, excluding the digit that was found
         * to b e smallest and added to the store. The new number gets returned so that 
         * smallest digit in the returned new number be found.
         */
         public static int getReducedNumber(int number, int digit) {
            System.out.println("Remove " + digit + " from " + number); 
            int newNumber = 0; 
    
            //flag to make sure we do not exclude repeated digits, in case there is 44
            boolean repeatFlag = false; 
            while(number > 0) {
                int t = number % 10; 
                //assume in loop one we found 1 as smallest, then we will not add one to the new number at all
                if(t != digit) {
                    newNumber = (newNumber * 10) + t; 
                } else if(t == digit) {
                    if(repeatFlag) {
                        System.out.println("Repeated min digit " + t + "found. Store is : " + store);
                        store = (store * 10) + t; 
                        System.out.println("Repeated min digit " + t + "added to store. Updated store is : " + store);
                        //we found another value that is equal to digit, add it straight to store, it is 
                        //guaranteed to be minimum
                    } else {
                        //skip the digit because its added to the store, in main method, set flag so 
                        // if there is repeated digit then this method add them directly to store
                        repeatFlag = true; 
                    }
                }
                number /= 10; 
            }
            System.out.println("Reduced number is : " + newNumber); 
            return newNumber; 
         }
    }
    

答案 4 :(得分:2)

我的算法:

import java.io.*;
import java.util.*;

public class Template implements Runnable {
private void solve() throws IOException {
    int n = nextInt();
    int m = nextInt();
    writer.println(n * m / 2);
}

public static void main(String[] args) {
    new Template().run();
}

BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;

public void run() {
    try {
        reader = new BufferedReader(new InputStreamReader(System.in));
        tokenizer = null;
        writer = new PrintWriter(System.out);
        solve();
        reader.close();
        writer.close();
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}

int nextInt() throws IOException {
    return Integer.parseInt(nextToken());
}

long nextLong() throws IOException {
    return Long.parseLong(nextToken());
}

double nextDouble() throws IOException {
    return Double.parseDouble(nextToken());
}

String nextToken() throws IOException {
    while (tokenizer == null || !tokenizer.hasMoreTokens()) {
        tokenizer = new StringTokenizer(reader.readLine());
    }
    return tokenizer.nextToken();
}
}

答案 5 :(得分:1)

添加一个非常简单的算法,不需要任何数据结构或花哨的数学,就像其他人一样。

f1

用语言:
1.在数字中每0打印一个0 2.在数字中每1打印1 ...

答案 6 :(得分:0)

这是一个简单的解决方案:

    public class SortDigits
    {
        public static void main(String[] args)
        {
            sortDigits(3413657);
        }

        public static void sortDigits(int num)
        {
            System.out.println("Number  : " + num);
            String number = Integer.toString(num);
            int len = number.length(); // get length of the number
            int[] digits = new int[len];
            int i = 0;
            while (num != 0)
            {
                int digit = num % 10;
                digits[i++] = digit; // get all the digits
                num = num / 10;
            }
            System.out.println("Digit before sorting: ");
            for (int j : digits)
            {
                System.out.print(j + ",");
            }
            sort(digits);
            System.out.println("\nDigit After sorting: ");
            for (int j : digits)
            {
                System.out.print(j + ",");
            }
        }
        //simple bubble sort 
        public static void sort(int[] arr)
        {
            for (int i = 0; i < arr.length - 1; i++)
                for (int j = i + 1; j < arr.length; j++)
                {
                    if (arr[i] > arr[j])
                    {
                        int tmp = arr[j];
                        arr[j] = arr[i];
                        arr[i] = tmp;
                    }
                }
        }
    }

答案 7 :(得分:0)

class SortDigits {
    public static void main(String[] args) {
        int inp=57437821;
        int len=Integer.toString(inp).length();
        int[] arr=new int[len];
        for(int i=0;i<len;i++)
        {
            arr[i]=inp%10;
            inp=inp/10;
        }
        Arrays.sort(arr);
        int num=0;
        for(int i=0;i<len;i++)
        {
            num=(num*10)+arr[i];
        }
        System.out.println(num);
    }    
}

答案 8 :(得分:0)

Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
int length = 0;
long tem = 1;
while (tem <= n) {
    length++;
    tem *= 10;
}

int  last=0;
int [] a=new int[length];
int i=0;
StringBuffer ans=new StringBuffer(4);
while(n!=0){
    last=n%10;
    a[i]=last;               
    n=n/10;
    i++;
}

int l=a.length;
 
for(int j=0;j<l;j++){
    for(int k=j;k<l;k++){
        if(a[k]<a[j]){
            int temp=a[k];
            a[k]=a[j];
            a[j]=temp;
        }
    }
}

for (int j :a) {
   ans= ans.append(j);
}
int add=Integer.parseInt(ans.toString());

System.out.println(add);

对于输入:

n=762941 ------->integer

我们得到输出:

149267      ------->integer

答案 9 :(得分:0)

import java.util.*;
class EZ
{
public static void main (String args [] )
{
    Scanner sc = new Scanner (System.in);
    System.out.println("Enter the number - ");
    int a=sc.nextInt();
    int b=0;
for (int i=9;i>=0;i--)
{
int c=a;
while (c>0)
{
    int d=c%10;             
    if (d==i)
    {
        b=(b*10)+d;
    }
    c/=10;                
}               
}
System.out.println(b);
}
}