Help with Recursive Merge Sort in Java Using Linked Lists

vayanui8

Well-Known Member
OP
Member
Joined
Nov 11, 2013
Messages
1,086
Trophies
0
XP
908
Country
United States
I'm currently working on programming a recursive mergesort method for my comp sci class. We are required to use Linked Lists for this method, and as I'm pretty terrible at both recursion and sorting algorithms this assignment has been giving me alot of trouble. We were given some starter code to get an idea, but I don't think my methods work properly, and Im getting a stack overflow error. Could somebody please help me?



Code:
import java.util.*;
import java.io.*;

/**
 *  Implements a recursive mergesort on a LinkedList data type
 *
 * [USER=353451]@Author[/USER]  G. Peck
 * @created  July 18, 2002
 *
 * Modified by Jason Quesenberry and Nancy Quesenberry
 * February 9, 2006
 */
public class MergeList{
  private  Scanner inFile;
  private String myFile;

  /**
  *  Open a file containing id/inventory pairs of data
  *
  * @param  fileName  File to be opened
  */
  public MergseList(String fileName)
  {
  try{
  inFile = new Scanner(new File(fileName));
  }
  catch(IOException i){
  System.out.println("Error: " + i.getMessage());
  }
  myFile = fileName;
  }

  /**
  *  Reads a file containing id/inv data pairs. The first line of the
  *  file contains the number of id/inventory integer pairs listed on
  *  subsequent lines.
  *
  * @param  list  Reference to LinkedList to which data will be added
  */
  public void readData(LinkedList<Item> list){
  int id = 0;
  int inv = 0;
  LinkedList<Item> tempList = new LinkedList<Item>();
  int count = 0;
  while (inFile.hasNext())
  {
  count++;
  if(count%2 == 0)
  {
  inv = Integer.parseInt(inFile.next()
);
  tempList.addFirst(new Item(id, inv));
  }
  else
  {
  id = Integer.parseInt(inFile.next());
  }  
  }  
  list = tempList;
  }

  /**
  *  Prints contents of list
  *
  * @param  list  linked list to be printed
  */
  public void printList(LinkedList list)
  {
  System.out.printf("%5s%16s","Id","Inventory\n");
  ListIterator<Item> listIterator = list.listIterator();  
  while(listIterator.hasNext())
  {
  Item harman = listIterator.next();
  System.out.printf("%5s%16s", harman.getId() , harman.getInv());
  System.out.println();   
  }
  System.out.println(); 
  System.out.println();
  }

  /**
  *  Splits listA into two parts. listA retains the first
  *  half of the list, listB contains the last half of
  *  the original list.
  *
  * @param  listA  Original list. reduced by half after split.
  * @param  listB  Contains last half of the original list
  */
  public void split(LinkedList<Item> listA, LinkedList<Item> listB)
  {  
  int temp = listA.size()/2;
  while (temp<listA.size())
  {
  listA.removeLast();
  listB.removeFirst();
  temp++;
  }

  }

  /**
  *  Two linked lists listA and listB are merged into a single
  *  linked list mergedList. They are placed in mergedList starting
  *  with the smallest item on either list and continue working up to
  *  to largest item.
  *
  * @param  listA  LinkedList in nondecreasing order
  * @param  listB  LinkedList in nondecreasing order
  * @return  List  containing all the values from lists listA
  *  and listB, in nondecreasing order
  */
  public LinkedList<Item> merge(LinkedList<Item> listA, LinkedList<Item> listB){
  // make sure the target list is empty
  LinkedList <Item> mergedList = new LinkedList <Item>();  
  ListIterator<Item> listIterator1 = listA.listIterator();  
  ListIterator<Item> listIterator2 = listB.listIterator();  
  while(listIterator1.hasNext() && listIterator2.hasNext())
  {
  Item jim = listIterator1.next();
  Item jam = listIterator2.next();
  if(jim.compareTo(jam) <= 0)
  {
  mergedList.addLast(jam);
  }
  else 
  {
  mergedList.addLast(jim);
  }
  }
  while(listIterator1.hasNext())
  {
  mergedList.addLast(listIterator1.next());
  }
  while(listIterator2.hasNext())
  {

  mergedList.addLast(listIterator2.next());

  }
  // start at mergedList left and right item
  // continue until either left or right list has no more value to add
  // use <= instead of < so if duplicate take from left so sort is stable

  // One of the next two while loops will execute.  It will be the one with some values
  // left on the list.
  return mergedList;
  }

  /***  The linked list is returned in sorted order.
  *  Sorted order has the smallest item first and the largest item
  *  last. The ordering is determined by the order defined in the
  *  Comparable class. The method uses the merge sort technique and
  *  must be recursive.
  *
  * @param  listA  LinkedList to be sorted
  * @return  LinkedList in sorted (nondecreasing) order
  */
  public LinkedList<Item> mergeSort(LinkedList <Item> listA){
  LinkedList <Item> listB =  (LinkedList) listA.clone();
  // Split the list in half.  If uneven then make left one larger.
  split(listA, listB);
  return merge(mergeSort(listA), mergeSort(listB));
  }

  /**
  *  Reverses the order of a list
  *
  * @param  list  LinkedList to be reversed
  * @return  List in reverse order
  */
  public LinkedList<Item> reverseList(LinkedList <Item>list)
  { 
  LinkedList <Item> listB =  new LinkedList<Item>();
  ListIterator<Item> listIterator = list.listIterator();  
  while(listIterator.hasNext())
  {
  listB.addLast(list.getFirst());
  }
  return listB;
  }
}
 

Site & Scene News

Popular threads in this forum

General chit-chat
Help Users
  • Psionic Roshambo @ Psionic Roshambo:
    I just want a Pokemon Hell Raiser fan game 😭
  • K3Nv2 @ K3Nv2:
    Anyone wanna play with my joydock
  • BigOnYa @ BigOnYa:
    Biomutant looks cool tho, may have to try that
  • Quincy @ Quincy:
    Usually when such a big title leaks the Temp will be the first to report about it (going off of historical reports here, Pokemon SV being the latest one I can recall seeing pop up here)
  • K3Nv2 @ K3Nv2:
    I still like how a freaking mp3 file hacks webos all that security defeated by text yet again
  • BigOnYa @ BigOnYa:
    They have simulators for everything nowdays, cray cray. How about a sim that shows you playing the Switch.
  • K3Nv2 @ K3Nv2:
    That's called yuzu
    +1
  • BigOnYa @ BigOnYa:
    I want a 120hz 4k tv but crazy how more expensive the 120hz over the 60hz are. Or even more crazy is the price of 8k's.
  • K3Nv2 @ K3Nv2:
    No real point since movies are 30fps
  • BigOnYa @ BigOnYa:
    Not a big movie buff, more of a gamer tbh. And Series X is 120hz 8k ready, but yea only 120hz 4k games out right now, but thinking of in the future.
  • K3Nv2 @ K3Nv2:
    Mostly why you never see TV manufacturers going post 60hz
  • BigOnYa @ BigOnYa:
    I only watch tv when i goto bed, it puts me to sleep, and I have a nas drive filled w my fav shows so i can watch them in order, commercial free. I usually watch Married w Children, or South Park
  • K3Nv2 @ K3Nv2:
    Stremio ruined my need for nas
  • BigOnYa @ BigOnYa:
    I stream from Nas to firestick, one on every tv, and use Kodi. I'm happy w it, plays everything. (I pirate/torrent shows/movies on pc, and put on nas)
  • K3Nv2 @ K3Nv2:
    Kodi repost are still pretty popular
  • BigOnYa @ BigOnYa:
    What the hell is Kodi reposts? what do you mean, or "Wut?" -xdqwerty
  • K3Nv2 @ K3Nv2:
    Google them basically web crawlers to movie sites
  • BigOnYa @ BigOnYa:
    oh you mean the 3rd party apps on Kodi, yea i know what you mean, yea there are still a few cool ones, in fact watched the new planet of the apes movie other night w wifey thru one, was good pic surprisingly, not a cam
  • BigOnYa @ BigOnYa:
    Damn, only $2.06 and free shipping. Gotta cost more for them to ship than $2.06
  • BigOnYa @ BigOnYa:
    I got my Dad a firestick for Xmas and showed him those 3rd party sites on Kodi, he loves it, all he watches anymore. He said he has got 3 letters from AT&T already about pirating, but he says f them, let them shut my internet off (He wants out of his AT&T contract anyways)
  • K3Nv2 @ K3Nv2:
    That's where stremio comes to play never got a letter about it
  • BigOnYa @ BigOnYa:
    I just use a VPN, even give him my login and password so can use it also, and he refuses, he's funny.
  • BigOnYa @ BigOnYa:
    I had to find and get him an old style flip phone even without text, cause thats what he wanted. No text, no internet, only phone calls.
    BigOnYa @ BigOnYa: I had to find and get him an old style flip phone even without text, cause thats what he wanted...