Friday, August 5, 2016

How to input numbers and print it in ascending order without using arrays and lists

When you try to sort a set of numbers in ascending series you can do it in many different ways . Among them you can use bubblesort ,heap data structure etc . but right now this tutorial is about how to sort a set of numbers in ascending series without using arrays and lists . Here is the code :

package asc;


import java.util.Scanner;

public class Asc {

  
    public static void main(String[] args) {
        String lottery="";
         long digit;
         long closet;
         long sorted;
         long hero =10;
       Scanner plot = new Scanner(System.in);
       System.out.println("No of numbers");
        long num = plot.nextInt();
       
       for( long i = 1;i<=num;i++){
           System.out.println("enter "+i+" number");
            long st = plot.nextInt();
           String crate = String.valueOf(st);
           closet = crate.length();
           if(closet==1){
               hero=10;
               
           }
           else if(closet ==2){
               hero = 100;
           }else if (closet==3){
               hero =1000;
               
           }else if (closet== 4){
               hero = 10000;
           }else if(closet == 5){
               hero = 100000;
       }
           lottery = String.valueOf(st)+lottery;
               long number = Integer.parseInt(lottery);
             sorted = 0;
 long digits = hero;
 long sortedDigits = 1;
boolean first = true;

while (number > 0) {
     digit = number % hero;

    if (!first) {

         long tmp = sorted;
         long nep= 1;
        for ( long k = 0; k < sortedDigits; k++) {
            
             long tmpDigit = tmp % hero;
            if (digit >= tmpDigit) {
                sorted = sorted/nep*nep*hero + digit*nep + sorted % nep;
                break;
            } else if (k == sortedDigits-1) {
                sorted = digit * digits + sorted;
            }
            tmp /= hero;
            nep *= hero;
        }
        digits *= hero;
        sortedDigits += 1;
    } else {
        sorted = digit;
    }

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


    }
    
}

now lets talk about how this works :

suppose you are given a number  486243      .How can you take out 3 which  is last number its simple . you do :

486243 % 10 or 486243 mod 10

to take out 4 you remove 3 by dividing 486243 by 10 and 

48624 % 10 or 48624 mod 10

but taking out is not enough you add it in ascending order by 

sorted = sorted/nep*nep*hero + digit*nep + sorted % nep;

and in this input number is in ascending order.





No comments:

Post a Comment