张德长

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

二分排序和冒泡排序的性能PK

 

对于数据量很大的情况,二分法排序相较于冒泡排序具有压倒性的性能优势

测试情况如下:

元素个数=200000,二分排序所用时间=13616743(Ticks)  1.3秒

元素个数=200000,冒泡排序所用时间=325,724,1227(Ticks) 325秒

冒泡排序与二分排序时间之比为=239.208541058607        

元素个数=100000,冒泡排序所用时间=811352144(Ticks)  81秒

元素个数=100000,二分排序所用时间=3274058(Ticks)  0.3秒

冒泡排序与二分排序时间之比为=247.812391839118

元素个数=10000,冒泡排序所用时间=8774623(Ticks)

元素个数=10000,二分排序所用时间=87368(Ticks)

冒泡排序与二分排序时间之比为=100.432915941764

元素个数=1000,冒泡排序所用时间=81145

元素个数=1000,二分排序所用时间=9128

冒泡排序与二分排序时间之比为=8.8896801051709

元素个数=100,二分排序所用时间=3860(Ticks)

元素个数=100,冒泡排序所用时间=6095(Ticks)

冒泡排序与二分排序时间之比为=1.57901554404145

二分查找方法

//降序排序集合的二分查找,返回值为应该插入的索引值
public static int BinarySearch(List<int> list, int value, int low, int high)
{
if (list.Count==0) return 0;
int middle = (low + high) / 2;
if (high ==low+ 1)
{
if (value <= list[high]) return high + 1;
else if (value <= list[low]) return low + 1;
else return low;
}
else if (high == low )
{
if (value <= list[high]) return high + 1;
else return high;
}
else
{
if (value > list[middle]) return BinarySearch(list, value, low, middle);
else return BinarySearch(list, value, middle, high);
}
}

排序方法

//二分排序-降序
static List<int> BinarySort(List<int > list)
{
List<int> result = new List<int>();
int insertPos;
for (int i = 0; i < list.Count; i++)
{
insertPos = BinarySearch(result, list[i], 0, result.Count - 1);
if (insertPos >= result.Count) result.Add(list[i]);
else result.Insert(insertPos, list[i]);
}
return result;
}
//冒泡排序-降序
static List<int> BubbleSort(List<int> list)
{
List<int> list2 = new List<int>(list);
int temp;
for (int i = 0; i < list2.Count; i++)
{
for (int j = i+1; j < list2.Count; j++)
{
if (list2[i] < list2[j])
{
temp = list2[i];
list2[i] = list2[j];
list2[j] = temp;
}
}
}
return list2;
}

测试方法

//二分排序和冒泡排序运行时间测试
static void test4()
{
List<int> list = new List<int>();
Random r = new Random();
for (int i = 0; i < 100; i++)
{
list.Add(r.Next(0, 100000000));
}
//二分排序
Stopwatch watch2 = new Stopwatch();
watch2.Start();
List<int> list2 = BinarySort(list);
watch2.Stop();
Console.WriteLine($"元素个数={list.Count},二分排序所用时间={watch2.ElapsedTicks}(Ticks)");
//冒泡排序
Stopwatch watch1 = new Stopwatch();
watch1.Start();
List<int> list1 = BubbleSort(list);
watch1.Stop();
Console.WriteLine($"元素个数={list.Count},冒泡排序所用时间={watch1.ElapsedTicks}(Ticks)");
double ratio = (double)watch1.ElapsedTicks / (double)watch2.ElapsedTicks;
Console.WriteLine($"冒泡排序与二分排序时间之比为={ratio}");
//DisplayList(list);
//DisplayList(list1);
//DisplayList(list);
//DisplayList(list2);
}

 运行结果

posted on   张德长  阅读(92)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示