|
|
<
代码:
- /// <summary>
- /// 堆排序办法。
- /// </summary>
- /// <param name="a">
- /// 待排序数组。
- /// </param>
- private void Heapsort(int[] a)
- {
- HeapSort_BuildMaxHeap(a); // 成立年夜根堆。
- Console.WriteLine("Build max heap:");
- foreach (int i in a)
- {
- Console.Write(i + " "); // 挨印年夜根堆。
- }
- Console.WriteLine("\r\nMax heap in each iteration:");
- for (int i = a.Length - 1; i > 0; i--)
- {
- HeapSort_Swap(ref a[0], ref a[i]); // 将堆顶元素战无序区的最初一个元故旧换。
- HeapSort_MaxHeaping(a, 0, i); // 将新的无序区调解为年夜根堆。
- // 挨印每次堆排序迭代后的年夜根堆。
- for (int j = 0; j < i; j++)
- {
- Console.Write(a[j] + " ");
- }
- Console.WriteLine(string.Empty);
- }
- }
- /// <summary>
- /// 由底背上建堆。由完整两叉树的性子可知,叶子结面是从index=a.Length/2开端,以是从index=(a.Length/2)-1结面开端由底背长进止年夜根堆的调解。
- /// </summary>
- /// <param name="a">
- /// 待排序数组。
- /// </param>
- private static void HeapSort_BuildMaxHeap(int[] a)
- {
- for (int i = (a.Length / 2) - 1; i >= 0; i--)
- {
- HeapSort_MaxHeaping(a, i, a.Length);
- }
- }
- /// <summary>
- /// 将指定的结面调解为堆。
- /// </summary>
- /// <param name="a">
- /// 待排序数组。
- /// </param>
- /// <param name="i">
- /// 需求调解的结面。
- /// </param>
- /// <param name="heapSize">
- /// 堆的巨细,也指数组中无序区的少度。
- /// </param>
- private static void HeapSort_MaxHeaping(int[] a, int i, int heapSize)
- {
- int left = (2 * i) + 1; // 左子结面。
- int right = 2 * (i + 1); // 左子结面。
- int large = i; // 暂时变量,寄存年夜的结面值。
- // 比力左子结面。
- if (left < heapSize && a[left] > a[large])
- {
- large = left;
- }
- // 比力左子结面。
- if (right < heapSize && a[right] > a[large])
- {
- large = right;
- }
- // 若有子结面年夜于本身便交流,使年夜的元素上移;而且把该年夜的元素调解为堆以包管堆的性子。
- if (i != large)
- {
- HeapSort_Swap(ref a[i], ref a[large]);
- HeapSort_MaxHeaping(a, large, heapSize);
- }
- }
- /// <summary>
- /// 交流两个整数的值。
- /// </summary>
- /// <param name="a">整数a。</param>
- /// <param name="b">整数b。</param>
- private static void HeapSort_Swap(ref int a, ref int b)
- {
- int tmp = a;
- a = b;
- b = tmp;
- }
复造代码
免责声明:假如进犯了您的权益,请联络站少,我们会实时删除侵权内乱容,感谢协作! |
1、本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,按照目前互联网开放的原则,我们将在不通知作者的情况下,转载文章;如果原文明确注明“禁止转载”,我们一定不会转载。如果我们转载的文章不符合作者的版权声明或者作者不想让我们转载您的文章的话,请您发送邮箱:Cdnjson@163.com提供相关证明,我们将积极配合您!
2、本网站转载文章仅为传播更多信息之目的,凡在本网站出现的信息,均仅供参考。本网站将尽力确保所提供信息的准确性及可靠性,但不保证信息的正确性和完整性,且不对因信息的不正确或遗漏导致的任何损失或损害承担责任。
3、任何透过本网站网页而链接及得到的资讯、产品及服务,本网站概不负责,亦不负任何法律责任。
4、本网站所刊发、转载的文章,其版权均归原作者所有,如其他媒体、网站或个人从本网下载使用,请在转载有关文章时务必尊重该文章的著作权,保留本网注明的“稿件来源”,并自负版权等法律责任。
|