I am really not 100% sure how to insert sort alphabetically from an array. This is what I have so far and any help is appreciated.
I am trying to use the insert sort algorithm to sort alphabetically in this project.
I am getting some errors in sorting, as well as runtime errors.
Thanks!
// The "Insertion_Sort_Example" class.
import java.awt.*;
import java.io.*;
import java.util.*;
public class SortPlanets
{
public static void main (int [] args)
{
String Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune, Pluto ;
String list [] = {Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune, Pluto}; // Array holding contents
System.out.println ("Array contents before sorting..."); // simple print statements to show proof of before sort
for(int i = 0; i < 5; i++) {
System.out.println(list[i]);
}
System.out.println ("");
System.out.println ("************************************");
insertSort (list); // call to insert function
System.out.println ("************************************"); // insert after
System.out.println ("Array contents after sorting...");
for(int i = 0; i < 5; i++) {
System.out.println(list[i]);
}
// Place your program here. 'c' is the output console
} // main method
public static void insertSort (String [] list) // sort function
{
for (int top = 1 ; top < list.length ; top++)
{
int item = list [top];
int i = top;
while (i > 0 && item < list [i - 1])
{
list [i] = list [i - 1];
i--;
}
list [i] = item;
System.out.print (list [0]);
System.out.print (" ");
System.out.print (list [1]);
System.out.print (" ");
System.out.print (list [2]);
System.out.print (" ");
System.out.print (list [3]);
System.out.print (" ");
System.out.print (list [4]);
System.out.println ();
}
}
} // Insertion_Sort_Example class