import java.awt.Color; import java.awt.event.ActionEvent; import javax.swing.JFrame; public class InsertionSortAnimation extends SortAnimation { protected int m = 0, n, temp; protected boolean movingOn = true; public void actionPerformed(ActionEvent evt) { if (movingOn) { movingOn = false; g.setColor(Color.GREEN); drawIndex(m); g.setColor(Color.RED); try { drawIndex(n = ++m); temp = a[m]; } catch (IndexOutOfBoundsException e) { finish(); } } else { g.setColor(Color.GREEN); if (n > 0 && a[n - 1] > temp) { a[n] = a[n - 1]; drawIndex(n--); g.setColor(Color.RED); } else { movingOn = true; } a[n] = temp; drawIndex(n); } } public static void main(String... args) { JFrame frame = new JFrame("Insertion sort animation"); frame.setSize(400, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setContentPane(new InsertionSortAnimation()); frame.setVisible(true); } }