//www.configure-all.com //Author: Sergey Skudaev //Bubble Sort Algorithm Demo //Copyright by Sergey Skudaev. All right reserved import java.applet.*; import java.awt.*; import java.awt.event.*; public class BSortArr extends Applet implements ActionListener, Runnable { char charArr[]; String input; int last; boolean exchange; Button temp; Button btncur; Label lcur; Label ltmp; Thread thread; boolean equalFlag = false; String [] arr = {"6", "2", "7", "3", "9", "1", "5", "4", "0", "8"}; Font f; private Button[] btnCh = new Button[10]; Button btnInput; Panel pbtn; Panel ptCh; Panel ptemp; Panel pcom; int count; public void init() { f = new Font("SanSerif", Font.BOLD, 20); setLayout(new BorderLayout()); temp = new Button(" "); ltmp = new Label("Temp"); ltmp.setForeground(Color.red); btncur = new Button(" "); btncur.setBackground(Color.yellow); lcur = new Label("Current"); lcur.setForeground(Color.red); pbtn = new Panel(); pbtn.setLayout(new FlowLayout()); ptCh = new Panel(); ptCh.setLayout(new FlowLayout()); ptemp = new Panel(); ptemp.setLayout(new FlowLayout()); pcom = new Panel(); pcom.setLayout(new BorderLayout()); for(int i = 0; i <10; i++) btnCh[i] = new Button(arr[i]); btnInput = new Button("Sort"); btnInput.addActionListener(this); pbtn.add(btnInput); last = btnCh.length; ptCh.add(btnCh[0]); ptCh.add(btnCh[1]); ptCh.add(btnCh[2]); ptCh.add(btnCh[3]); ptCh.add(btnCh[4]); ptCh.add(btnCh[5]); ptCh.add(btnCh[6]); ptCh.add(btnCh[7]); ptCh.add(btnCh[8]); ptCh.add(btnCh[9]); ptemp.add(btncur); ptemp.add(lcur); ptemp.add(temp); ptemp.add(ltmp); pcom.add(ptCh, BorderLayout.NORTH); pcom.add(ptemp, BorderLayout.SOUTH); add(pcom, BorderLayout.NORTH); add(pbtn, BorderLayout.SOUTH); } public void actionPerformed(ActionEvent e) { if(e.getSource() == btnInput) run(); } public void run() { String lblBtnCh; int curr = 0; boolean sorted = false; while((curr < last)&&(sorted == false)) { sorted = true; int walker = last - 1; while(walker > curr) { try { Thread.sleep(2000); } catch(InterruptedException e) { break; } for(int l = 0; l< last; l++) btnCh[l].setBackground(Color.lightGray); btnCh[walker].setBackground(Color.red); btnCh[curr].setBackground(Color.yellow); btnCh[walker-1].setBackground(Color.red); lblBtnCh = btnCh[walker].getLabel(); if(lblBtnCh.compareTo(btnCh[walker-1].getLabel()) < 0) { sorted = false; temp.setLabel(btnCh[walker].getLabel()); btnCh[walker].setLabel(btnCh[walker-1].getLabel()); btnCh[walker-1].setLabel(temp.getLabel()); } walker--; } curr++; } } public void paint(Graphics g) { g.setFont(f); g.setColor(Color.red); g.drawString("Bubble Sort Illustration", 200, 150); } }