1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Java insertionsort recursive

  1. Sep 27, 2011 #1
    im having a little trouble getting started with this. it is for an array of strings.

    would i do insertion sort the same was as if it was an array of ints or doubles but use the compareTo method to see if i should switch two elements?


    this is my attempt so far, it wont compile due to the a[key].

    a hint or suggestion would be appreciated. thank you

    Code (Text):
      public void insertionSort()
        {
            insertionSort(a.length-1);
        }
       
       
       
       
        private void insertionSort(int n)
        {
            String temp;
            if(n <= 1)
            {
            //Do nothing, easiest case
            }
     
            else
            {
            for(int i = 1; i < a.length; i++)
            {
            int j;
            String key = a[i];
           
                while((j >= 0) && (a[i].compareTo(a[key]) > 0))
                {
                a[i+1] = a[i];
                j--;
                }
                a[i+1] = key;
            }  
       
            insertionSort(n-1);
       
            }
        }
     
  2. jcsd
  3. Sep 28, 2011 #2

    Mark44

    Staff: Mentor

    I've taken the liberty of adjusting your indentation. You're getting better at it, but it still needed a few tweaks.
    The problem with a[key] is that you are trying to use a string to index into an array - you can't do that. The array index needs to be an integral type, like int or long.

    You don't show enough of your code for me to understand what you're trying to do, so I can't offer any alternatives.

    One thing you can do to improve your code is to change your outer if - else block. Instead of this...
    Code (Text):
    if(n <= 1)
    {
        //Do nothing, easiest case
    }
     
    else
    {
       ...
    }
     
    you can do this...
    Code (Text):
    if(n > 1)
    {
        ...
    }
     
    You don't need an else block.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Java insertionsort recursive
  1. Recursive function (Replies: 16)

  2. Recursion Tree (Replies: 3)

  3. Recursive calls (Replies: 15)

Loading...