How Do You Implement Recursive Insertion Sort for Arrays of Strings in Java?

  • Context: Comp Sci 
  • Thread starter Thread starter apiwowar
  • Start date Start date
  • Tags Tags
    Java
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
1 reply · 6K views
apiwowar
Messages
94
Reaction score
0
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 won't compile due to the a[key].

a hint or suggestion would be appreciated. thank you

Code:
  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);
	
		}
	}
 
Physics news on Phys.org
apiwowar said:
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 won't compile due to the a[key].

a hint or suggestion would be appreciated. thank you
I've taken the liberty of adjusting your indentation. You're getting better at it, but it still needed a few tweaks.
apiwowar said:
Code:
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);
   }
}

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:
if(n <= 1)
{
    //Do nothing, easiest case
}
  
else
{
   ...
}

you can do this...
Code:
if(n > 1)
{
    ...
}
You don't need an else block.