Top Topics in our Forum';
Math Video Game! Play Fraction Balls!

A+    A−    B  
Algebra
Games
Geometry
Interactive
Trigonometry
Forum




AddThis Social Bookmark Button

Searching & Sorting Recursions In Java

Recursively Sorting Array of Strings


Look at the Code Below and Try Running it. Be prepared to explain how it works
Your assignment: Rewrite the recursive selectSortStep() method in a normal iteraive (loop-based way). Also you must change listItems to be an ArrayList of Strings (practice for the AP test.) . ArrayList syntax reminder

import java.util.ArrayList;;


public class RecursiveSort2 {
	
	static String[] listItems = new String[7];
	static int numItems = listItems.length;
	

	//below is the recursive selection sort method
	static void selectSortStep(int passCount){

		String temp; int sIndex;
		if (passCount < numItems-1)
	    {
	      int minIndex = passCount;
		// find index of smallest remaining
				for (sIndex = passCount + 1; sIndex< numItems; sIndex++)
					if(listItems[sIndex].compareTo(listItems[minIndex])<0)
						minIndex = sIndex;
					temp = listItems[minIndex];     //swap
					listItems[minIndex] = listItems[passCount];
					listItems[passCount] = temp;
					selectSortStep(passCount + 1);
					
			}
	}
	 
	 
	public static void main(String[] args){
		listItems[0] = "Bob";
		listItems[1] = "Andrew";
		listItems[2] = "Cody";
		listItems[3] = "Douglas";
		listItems[4] = "Richie";	
		listItems[5] = "Peter";	
		listItems[6] = "Matt";	

		selectSortStep(listItems.length);
		
		for(String s:listItems) System.out.println(s);
		
		
			
		
}
	
		
 static void selectSort()
	// Sorts array into ascending order
	 
	{
		String temp; int passCount; int sIndex;
		int minIndex;     // index of minimum so far
		for(passCount = 0; passCount <numItems-1; passCount++)
			{
				minIndex = passCount;
				// find index of smallest remaining
				for (sIndex = passCount + 1; sIndex< numItems; sIndex++)
					if(listItems[sIndex].compareTo(listItems[minIndex])<0)
						minIndex = sIndex;
					temp = listItems[minIndex];     //swap
					listItems[minIndex] = listItems[passCount];
					listItems[passCount] = temp;
					
			}
	}		
	
}



Top
Welcome Guest
Please Log in or register
Who's online: 8 Guests, 0 Users :        Please welcome DDDDepressionnnn, our newest member.
AddThis Social Bookmark Button Page copy protected against web site content infringement by Copyscape