Legoprogrammer
4/9/2019 - 4:47 PM

Insertion Sort (takes directional input)

A basic insertion sort method. Implementation code in text file at bottom. When passed the integer 1, it sorts in ascending order. When passed the integer 2, it sorts in descending order. When passed any other number the program currently terminates.

public static Movie[] sortByYear(Movie[] array, int direction)
{
  Movie[] sortedMovies = new Movie[array.length];
  for(int i = 0; i < array.length; i++)
  {
    Movie next = array[i];
    int insertIndex = 0;
    int k = i;
    
    while(k > 0 && insertIndex == 0)
    {
      if(direction == 1) {
          if (next.getYear() > sortedMovies[k - 1].getYear()) {
            insertIndex = k;
          } else {
            sortedMovies[k] = sortedMovies[k - 1];
          }
          k--;
        } else if(direction == 2)
        {
          if (next.getYear() < sortedMovies[k - 1].getYear()) {
            insertIndex = k;
          } else {
            sortedMovies[k] = sortedMovies[k - 1];
          }
          k--;
      } else{
        System.out.println("Illegal direction. Program Terminating...");
        System.exit(-1);
      }
    }
  }
}
Movie can be replaced by the name of the class that the Array is made of. For example, Integer, String, or Double.

Year can be replaced by any getter method from that class.

System.exit on line 29 can be replaced with another error code.

To use simply call unsortedArray = sortByYear(unsortedArray);