Reputation: 21
I have an assignment for school and i got a bit stuck in the process.
The idea is to make a program in C# where you can visualize how the insertion sorting algorithm works and for that I'm using an array of buttons with random generated numbers.
It colours green for comparison and red for swapping.
Why do the buttons remain coloured?
public partial class Form1 : Form
{
Button[] but;
int[] A;
int nr_den = 0;
int s1 = 0;
int s2 = 0;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
nr_den = Convert.ToInt16(textBox1.Text);
s1 = Convert.ToInt16(textBox2.Text);
s2= Convert.ToInt16(textBox3.Text);
A = new int[nr_den+1];
Random r = new Random();
for (int i = 1; i <= nr_den; i++)
{
A[i] = r.Next(s1, s2);
}
but = new Button[nr_den + 1];
for (int i = 1; i <= nr_den; i++)
{
but[i] = new Button();
but[i].Text = A[i].ToString();
but[i].Width = 40;
but[i].Height = 40;
flowLayoutPanel1.Controls.Add(but[i]);
}
}
public void exchange(int[] A, int m, int n)
{
string s;
int temp;
but[m].BackColor = Color.Red;
System.Threading.Thread.Sleep(400);
but[n].BackColor = Color.Pink;
System.Threading.Thread.Sleep(400);
temp = A[m];
s = but[m].Text;
A[m] = A[n];
but[m].Text = but[n].Text;
A[n] = temp;
but[n].Text = s;
but[m].Refresh();
but[n].Refresh();
}
public void sort(int[] A)
{
int i, j;
int N = A.Length;
for (j = 1; j < N; j++)
{
for (i = j; i > 0 && A[i] < A[i - 1]; i--)
{
but[i-1].BackColor = Color.Green;
System.Threading.Thread.Sleep(400);
but[i].BackColor = Color.GreenYellow;
System.Threading.Thread.Sleep(400);
but[i].Refresh();
but[i - 1].Refresh();
exchange(A, i, i - 1);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
for (int i=1;i<=nr_den;i++)
richTextBox1.Text += A[i]+ " ";
richTextBox1.Text += " \n";
sort(A);
}
private void button3_Click(object sender, EventArgs e)
{
flowLayoutPanel1.Controls.Clear();
}
}
Upvotes: 0
Views: 4073
Reputation: 118
restore color after completion
public void sort(int[] A)
{
int i, j;
int N = A.Length;
for (j = 1; j < N; j++)
{
for (i = j; i > 0 && A[i] < A[i - 1]; i--)
{
but[i - 1].BackColor = Color.Green;
System.Threading.Thread.Sleep(400);
but[i].BackColor = Color.GreenYellow;
System.Threading.Thread.Sleep(400);
but[i].Refresh();
but[i - 1].Refresh();
exchange(A, i, i - 1);
but[i-1].BackColor = SystemColors.Control;
but[i].BackColor = SystemColors.Control;
}
}
}
restore color during process
public void sort(int[] A)
{
int i, j;
int N = A.Length;
for (j = 1; j < N; j++)
{
for (i = j; i > 0 && A[i] < A[i - 1]; i--)
{
but[i - 1].BackColor = Color.Green;
System.Threading.Thread.Sleep(400);
but[i].BackColor = Color.GreenYellow;
System.Threading.Thread.Sleep(400);
but[i].Refresh();
but[i - 1].Refresh();
exchange(A, i, i - 1);
but[i-1].BackColor = SystemColors.Control;
but[i].BackColor = SystemColors.Control;
System.Threading.Thread.Sleep(400);
but[i].Refresh();
but[i - 1].Refresh();
}
}
}
Upvotes: 1