# 大家有用C#写过排序算法吗？为什么我写的快速排序比插入排序还慢！？

lbiori241 2006-10-30 08:39:01

c#的内部机制我不太清楚，期待高手出来解答。

public float[] Sort_Insert(float[] sequence, int low, int high)//插入排序
{
sorted = new float[sequence.Length];
sequence.CopyTo(sorted,0);
Stopwatch watch = new Stopwatch();//实例化跑马表
watch.Start();//开始计时
//-------------------
int i;
float temp;
for (int j = low + 1; j <= high; j++)
{
i = j - 1;
temp = sorted[j];
while (i >= low && sorted[i] > temp)//依次将j以前的元素后移一位
{
sorted[i + 1] = sorted[i];
i--;
}
sorted[i + 1] = temp;
}
//-------------------
watch.Stop();//计时停止
lbTime.Text = watch.ElapsedMilliseconds.ToString() + " ms";//得到运行的时间，毫秒级
return sorted;
}

-------------------------------------------------------------
public float[] Sort_Quick(float[] sequence, int low, int high)//快速排序
{
sorted = new float[sequence.Length];
sequence.CopyTo(sorted, 0);
Stopwatch watch = new Stopwatch();//实例化跑马表
watch.Start();//开始计时
//-------------------
int pivot;//枢轴
if (low < high)
{
pivot = Partition1(sorted, low, high);
Sort_Quick(sorted, low, pivot - 1);
Sort_Quick(sorted, pivot + 1, high);
}
//-------------------
watch.Stop();//计时停止
lbTime.Text = watch.ElapsedMilliseconds.ToString() + " ms";//得到运行的时间，毫秒级
return sorted;
}

private int Partition1(float[] sequence, int low, int high)
{
float temp = sequence[high];
int i = low - 1;
for (int j = low; j <= high - 1; j++)
{
if (sequence[j] <= temp)
{
i++;
Exchange(i, j);//交换两数
}
}
Exchange(i + 1, high);//交换两数
return i + 1;
}
...全文
191 4 打赏 收藏 举报

4 条回复

lbiori241 2006-10-31
• 打赏
• 举报

10000个随机样本用快排只用5ms
liujia_0421 2006-10-30
• 打赏
• 举报

shrinerain 2006-10-30
• 打赏
• 举报

sequence.CopyTo(sorted, 0);

lbiori241 2006-10-30
• 打赏
• 举报

10.8w+

.NET技术 C#

2006-10-30 08:39