Search code examples
javaarraysrecursioninsertion

java insertion sort recursive


i have an array and have to sort them using insertion sort. i tried to use the compareTo method to run through the array and see whats bigger. I ran into a problem because i was trying to reference an array index with a string which obviously didntwork (thats at compareTo(a[key])).

any suggestions or hints as to how to do this would be appreciated.

this is what i have so far. is it a good start? or a start in the right direction?

 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);

        }
    } 

Solution

  • Replace the inner loop as follows:

    j = i - 1;  //initialize j!!!
    String key = a[i];   //take value
    while((j >= 0) && (a[j].compareTo(key) > 0)){//Compare with key!!!
         a[j+1] = a[j];
         j--;
    }
    a[j + 1] = key; //index is j here!!!!