I had an exam this morning i couldn't figure it out. it looks like doesn't matter now because the exam was this
morning but i still want to know how to do it....
i have 2 button: Add(btn_ADD) and Sort(btn_SORT)
1 textbox ( textbox1 )and 1 listbox (listbox1)
Everything is working except for 1 problem:
The teacher add 3 string: 12345
12
abc
(my code is sorting like this, and this is wrong)
Then click the sort buttin: abc
12345
12
(how to sort like this?)
the correct sorting would be: abc
12
12345
struct SString
{
public string m_Sname;
public SString(string s)
{
m_Sname = s;
}
public override string ToString()
{
return string.Format(m_Sname.ToString());
}
}
List<SString> m_list = new List<SString>();
public Form1()
{
InitializeComponent();
}
private void btn_ADD_Click(object sender, EventArgs e)
{
try
{
SString temp = new SString(textBox1.Text);
m_list.Add(temp);
listBox1.Items.Add(temp.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btn_SORT_Click(object sender, EventArgs e)
{
SString[] sort;
sort = m_list.ToArray();
BubbleSort_string(sort);
listBox1.Items.Clear();
m_list.Clear();
foreach (SString n in sort)
{
m_list.Add(n);
listBox1.Items.Add(n.ToString());
}
}
private void BubbleSort_string(SString[] ArrayOfString)
{
SString tempS = new SString();
//number of passes through array equals number of elements - 1
for (int iPass = 0; iPass < ArrayOfString.Length - 1; iPass++)
{
//scan through the array looking for swaps
for (int iScan = 0; iScan < ArrayOfString.Length - 1; iScan++)
{
char a = string.Format(ArrayOfString[iScan].m_Sname).ToCharArray()[0];
char b = string.Format(ArrayOfString[iScan + 1].m_Sname).ToCharArray()[0];
int x = (int)a;
int y = (int)b;
if (x < y)
{
tempS = ArrayOfString[iScan];
ArrayOfString[iScan] = ArrayOfString[iScan + 1];
ArrayOfString[iScan + 1] = tempS;
}
}
}
return;
}