比较经常使用IComparable接口,实现类的排序今天一时心血来潮,单步调试了一下IComparable接口的运行顺序,结果发现就2个值的Sort,它都运行了CompareTo方法5次
3个值的Sort,运行了CompareTo方法7次,4个值则16次
比一般的冒泡排序效率低多了
这是为什么呢?难道Sort排序效率就是这么低?代码: public partial class ztest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<test> arr = new List<test>();
test tmp = new test();
arr.Add(tmp);
tmp.a = "6"; tmp = new test();
arr.Add(tmp);
tmp.a = "5"; tmp = new test();
arr.Add(tmp);
tmp.a = "4"; arr.Sort();
Response.Write(test.cnt.ToString());
}
} public class test:IComparable<test>
{
public static int cnt = 0;
public string a;
public int CompareTo(test other)
{
cnt++;
return this.a.CompareTo(other.a);
}
}
3个值的Sort,运行了CompareTo方法7次,4个值则16次
比一般的冒泡排序效率低多了
这是为什么呢?难道Sort排序效率就是这么低?代码: public partial class ztest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<test> arr = new List<test>();
test tmp = new test();
arr.Add(tmp);
tmp.a = "6"; tmp = new test();
arr.Add(tmp);
tmp.a = "5"; tmp = new test();
arr.Add(tmp);
tmp.a = "4"; arr.Sort();
Response.Write(test.cnt.ToString());
}
} public class test:IComparable<test>
{
public static int cnt = 0;
public string a;
public int CompareTo(test other)
{
cnt++;
return this.a.CompareTo(other.a);
}
}
解决方案 »
- C# 中如何使用AxShockwaveFlash控件
- C#修改listView控件中 资料 级别!! 求教!!!!!
- 求各位大神忙帮写个.NET后台代码 跪求
- 兄弟们,求救了,谢谢了!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
- 想编个music播放器!!
- C#WINDOW窗体在TEXTBOX中输入如下内容,因该怎么算?
- C# Winform中使用mapxtreme
- 安装Vistual Studio 2012出现问题
- c#及数据库的高手帮帮忙
- 一个private函数中调用另一个private函数中的变量,该如何实现?
- C#如何只运行程序的一个实例?发现已有同样的实例在运行,此时如何让这个已运行的实例窗口显示在桌面的最前面?
- 打开网页的同时直接触动登陆按钮
我用 Array.Sort(Test[]) 在 .NET Framework 下做个测试,结果正常
using System.Collections.Generic;class Program : IComparable<Program>
{
public static int cnt = 0;
public int i; public Program(int i)
{
this.i = i;
}
public int CompareTo(Program other)
{
cnt++;
return i.CompareTo(other.i);
} static void Main(string[] args)
{
List<Program> list = new List<Program>();
Random r = new Random(123456);
for (int i = 0; i < 100; i++)
{
list.Add(new Program(r.Next()));
}
list.Sort(); Console.WriteLine(Program.cnt); //803
}
}
3个值,冒泡的话,应该3次就够了
int count = 0;
int[] arr1 = {4, 3, 2, 1 };
for (int i = 0; i < arr1.Length; i++)
{
for (int j = i + 1; j < arr1.Length; j++)
{
count++;
if (arr1[i] > arr1[j])
{
int tmp1 = arr1[i];
arr1[i] = arr1[j];
arr1[j] = tmp1;
}
}
}
Response.Write(count.ToString() + "<hr>");