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
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;
}
VulpesPosted Dec 17, 2011, 6:42 AM
if (x < y)
to this:
if (x > y)
Jonathan CrispePosted Dec 16, 2011, 9:43 PM
VulpesPosted Dec 14, 2011, 11:40 AM
Consequently, whether "12345" sorts before "12" or not is indeterminate because both of them start with the same character which has an ASCII value of 49.
However, both of them will always sort after "abc" because 'a' has an ASCII value of 97.
Is this in fact what you were told to do or are you supposed to sort on the whole string, not just the first character?