求排序写法改进
对一组字符串中的数字进行大小排序,如下方法得到了正确的结果。
private void butok_Click(object sender, EventArgs e)
{
string str="8 9 3 16 10 10 8 6 10 12";
string strTemp = "";
string[] Arr = arrayList(str);
for (int i = 0; i < Arr.Length; i++)
{
strTemp = strTemp + Arr[i].ToString() + " ";
}
strTemp = strTemp.Substring(0, strTemp.Length - 1);
textBox1.Text = strTemp;
}
private string[] arrayList(string strTemp)
{
string[] a = strTemp.Split(' ');
string temp;
for (int i = 0; i < a.Length; i++)
{
for (int j = i + 1; j < a.Length; j++)
{
if (Convert.ToDouble(a[i]) > Convert.ToDouble(a[j]))
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a;
}
class Program
{
static void Main(string[] args)
{
string str = "8 9 3 16 10 10 8 6 10 12";
string[] arr = str.Split(' ');
IndexNum[] arrIndexNum = new IndexNum[arr.Length];
for (int i = 0; i < arrIndexNum.Length; i++)
{
arrIndexNum[i] = new IndexNum() { iIndex = i, iValue = Convert.ToDouble(arr[i]) };
}
var order = arrIndexNum.OrderBy(indexNum => indexNum.iValue).Select(indexNum=>string.Format("({0}:{1})", indexNum.iValue,indexNum.iIndex));
Console.WriteLine(string.Join("", order));
Console.ReadLine();
}
}
public class IndexNum
{
public int iIndex;
public double iValue;
}