Results 1 to 2 of 2
  1. #1
    Join Date
    Dec 2011
    Posts
    7
    Rep Power
    0

    Default How to use mergesort to sort a list of names?

    Hi, I'm trying to sort a list of names alphabetically, case-insensitive by using the mergesort technique.
    I wrote this code and when I trace it through on paper with an example array of names, it should work, but when I run it with an actual txt file, it's not correctly alphabetical.
    I'd appreciate it if someone could take a look at my code and give me some ideas on what my problem might be.
    Thanks in advance!

    Java Code:
    public static void mergeSort(String[] names)
    	{
    		if (names.length >= 2)
    		{
    			String[] left = new String[names.length/2];
    			String[] right = new String[names.length-names.length/2];
    			
    			for (int i = 0; i < left.length; i++)
    			{
    				left[i] = names[i];
    			}
    			for (int i = 0; i < right.length; i++)
    			{	
    				right[i] = names[i + names.length/2];
    			}
    
    			mergeSort(left);
    			mergeSort(right);
    			merge(names, left, right);
    		}
    	}
        
       // pre : result is empty; list1 is sorted; list2 is sorted
       // post: result contains result of merging sorted lists;
       // add merge method below
    	
    	public static void merge(String[] names, String[] left, String[] right)
    	{
    		int i1 = 0;
    		int i2 = 0;
    		
    		for (int i = 0; i < names.length; i++)
    		{
    			if (i2 >= right.length || (i1 < left.length 
                            && left[i1].compareToIgnoreCase(right[i1])<0))
    			{
    				names[i] = left[i1];
    				i1++;
    			} else
    			{
    				names[i] = right[i2];
    				i2++;				
    			}
    		}
    	}	
    }

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,939
    Rep Power
    8

    Default Re: How to use mergesort to sort a list of names?

    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

Similar Threads

  1. Replies: 1
    Last Post: 03-25-2012, 09:25 PM
  2. Sort Student Names and Grades
    By son012189 in forum New To Java
    Replies: 5
    Last Post: 10-24-2011, 04:04 AM
  3. Replies: 26
    Last Post: 05-13-2011, 03:54 PM
  4. array to sort names in alphabetical order
    By leoshiner in forum New To Java
    Replies: 6
    Last Post: 05-01-2011, 12:28 PM
  5. How to sort a list using Bubble sort algorithm
    By Java Tip in forum Algorithms
    Replies: 3
    Last Post: 04-29-2008, 08:04 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •