I have to sort the bars but i have to show them sort, by delaying it. Can someone help me add delay to make it work. I used Selection Sort ---

import java.applet.Applet; 
import java.awt.*; 
import java.util.Random; 
import javax.swing.*; 

public class SelectionSort extends JApplet 
{ 
	//Variables and arrays 
	Rectangle[] bar_array = new Rectangle[10]; 
	int minIndex; 
	
	public void init() 
	{ 
		final int NUM_BARS = 10; 
		int x = 9, height; 
		bar_array = new Rectangle[10]; 
		
		Random generator = new Random(); 
		height = generator.nextInt(300) + 1; 
		
		for (int i = 0; i < NUM_BARS; i++) 
		{ 
			bar_array[i] = new Rectangle(x, 300-height, 30, height); 
			height = generator.nextInt(300) + 1; 
			x = x + (30 + 9); 
		} 
		
		insertionSort();
	} 
	
	
	// Paints bars of varying heights, tracking the tallest and 
	// shortest bars, which are redrawn in color at the end. 
	public void paint (Graphics page) 
	{
		int x; 
		setBackground (Color.black); 
		
		page.setColor (Color.blue); 
		x = 9; 
		
		for (int i = 0; i < bar_array.length; i++) 
		{ 
			Dimension d = bar_array[i].getSize(); 
			Point p = bar_array[i].getLocation(); 
			page.fillRect(p.x, p.y, d.width, d.height); 
			
			x = x + (30 + 9); 
		} 
	} 
		
	// Sorts the specified array of rectangles using the selection 
	// sort algorithm. 
	
	void selectionSort() 
	{ 
			
		for(int i = 0; i < bar_array.length - 1; i++ ) 
		{ 
			int minIndex = i; 
			for( int j = i + 1; j < bar_array.length; j++ ) 
			{
 
				if( bar_array[j].height < bar_array[minIndex].height ) 
				{ 
					minIndex = j;
				}
			} 
			
			if(minIndex > i) 
			{ 
				Rectangle temp = bar_array[i]; 
				bar_array[i] = bar_array[minIndex]; 
				bar_array[minIndex] = temp; 
				
				int tempX = bar_array[i].x; 
				bar_array[i].x = bar_array[minIndex].x; 
				bar_array[minIndex].x = tempX; 
			} 
				
			//Delay	
			/*
			try
			{
				Thread.sleep(200); // do nothing for 1000 miliseconds (1 second)
			}
			catch (InterruptedException e){
	        }*/			
			
		} 
	}
	
	 
}

I have the delay code in there but, i dont know where to put it. I tried to put it several places, but it still didn't work.

You should probably have code where you catch the Exception. No use catching it if you don't know when you caught it. And the question of where to put the Thread.sleep() call depends on where you want the pause to be. Right after you have executed all the code that displays whatever you want to display, put the Thread.sleep there. Also, the problem is probably that you have Thread.sleep(200). That is a pause of 200 milliseconds, or 1/5 of a second. Try putting Thread.sleep(2000) - you may notice a change.

This article has been dead for over six months. Start a new discussion instead.