C#QuickSort太慢了
发布时间:2020-12-16 09:31:49 所属栏目:百科 来源:网络整理
导读:我现在正在学习不同类型的排序,我发现,从某一点开始,我的QuickSort算法根本不能快速运行. 这是我的代码: class QuickSort { // partitioning array on the key so that the left part is =key,right part key private int Partition(int[] arr,int start,in
我现在正在学习不同类型的排序,我发现,从某一点开始,我的QuickSort算法根本不能快速运行.
这是我的代码: class QuickSort { // partitioning array on the key so that the left part is <=key,right part > key private int Partition(int[] arr,int start,int end) { int key = arr[end]; int i = start - 1; for (int j = start; j < end; j++) { if (arr[j] <= key) Swap(ref arr[++i],ref arr[j]); } Swap(ref arr[++i],ref arr[end]); return i; } // sorting public void QuickSorting(int[] arr,int end) { if (start < end) { int key = Partition(arr,start,end); QuickSorting(arr,key - 1); QuickSorting(arr,key + 1,end); } } } class Test { static void Main(string[] args) { QuickSort quick = new QuickSort(); Random rnd = new Random(DateTime.Now.Millisecond); int[] array = new int[1000000]; for (int i = 0; i < 1000000; i++) { int i_rnd = rnd.Next(1,1000); array[i] = i_rnd; } quick.QuickSorting(array,array.Length - 1); } } 在一百万个元素的数组上运行此代码大约需要15秒.例如,MergeSort或HeapSort在不到一秒的时间内完成相同的操作. 你能告诉我为什么会这样吗? 解决方法
您的排序速度有多快以及您应该使用哪种算法取决于您输入的大量数据.它是随机的,几乎排序的,反转的等等.
有一个非常好的页面,说明了不同的排序算法如何工作: > Sorting Algorithm Animations (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |