Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    May 2004
    Location
    Norway
    Posts
    23
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Insertion sort - i need to turn it around - how?

    I have a "insertion sort" which works perfectly. It does the normal thing, it puts sorted values in a "left" part, and have the unsorted values in the "right" part. Works smoothly. What I want to do, is to turn this around. I want to start at the end, and have the sorted values to the right, and then get the next unsorted values (in the left part), and sort it among the sorted values to the right.

    Attached is the code that works. Can someone help me, turn it around? Thanks alot...

    Code:
    class tabell{
    	private long[] a;		
    	private int nElementer; 
    	
    	
    	public tabell(int max){
    		a = new long[max];
    		nElementer = 0;
    	}
    	
    	public int getLength(){
    		return a.length;
    	}
    	
    	public void insert(long value) {
       		a[nElementer] = value;       
       		nElementer++;          
       }
       
    	public void displayTableValues() {
    		for(int j=0; j<nElementer; j++)    
    		System.out.print(a[j] + " "); 		
        	System.out.println("");
    	}
       
       public void insertionSort(){
        	int in, out;
        	for(out=1; out<nElementer; out++){  
    	    	long temp = a[out];      
    	    	in = out;           
    	    	while(in>0 && a[in-1] >= temp) { 
    	    		 a[in] = a[in-1];      
    	    		 --in;            
    	    	}
    	    	a[in] = temp;         
    	    	displayTableValues();
       		} 
       } 
         
       
       }

  • #2
    New Coder
    Join Date
    May 2004
    Location
    Norway
    Posts
    23
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Solved it

    public void innstikkSorteringBakfra(){
    int in, out;
    for(out=nElementer-1; out >= 0; out--){
    long temp = a[out];
    in = out;
    while(in < nElementer-1 && a[in+1] <= temp) {
    a[in] = a[in+1];
    ++in;
    }
    a[in] = temp;
    System.out.println("Jobber med sortering....");
    displayTableValues();
    }
    }


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •