本文概述
- 复杂
- 算法
- C程序
- Java程序
- C#程序
【堆排序算法实现】堆排序基本上以递归方式执行两个主要操作。
- 使用ARR的元素构建堆H。
- 重复删除阶段1中形成的堆的根元素。
复杂 | 最好的情况 | 平均情况 | 最差的情况 |
---|---|---|---|
Time Complexity | Ω(n对数(n)) | θ(n log(n)) | O(n对数(n)) |
Space Complexity | O(1) |
- 步骤1:[Build H堆]对i = 0重复N-1次调用INSERT_HEAP(ARR, N, ARR [i])[结束循环]
- 步骤2:重复删除根元素当N> 0时重复CALL Delete_Heap(ARR, N, VAL)SET N = N + 1 [LOOP LOOP]
- 步骤3:结束
#include<
stdio.h>
int temp;
void heapify(int arr[], int size, int i){int largest = i;
int left = 2*i + 1;
int right = 2*i + 2;
if (left <
size &
&
arr[left] >
arr[largest])largest = left;
if (right <
size &
&
arr[right] >
arr[largest])largest = right;
if (largest != i){temp = arr[i];
arr[i]= arr[largest];
arr[largest] = temp;
heapify(arr, size, largest);
}}void heapSort(int arr[], int size){int i;
for (i = size / 2 - 1;
i >
= 0;
i--)heapify(arr, size, i);
for (i=size-1;
i>
=0;
i--){temp = arr[0];
arr[0]= arr[i];
arr[i] = temp;
heapify(arr, i, 0);
}}void main(){int arr[] = {1, 10, 2, 3, 4, 1, 2, 100, 23, 2};
int i;
int size = sizeof(arr)/sizeof(arr[0]);
heapSort(arr, size);
printf("printing sorted elements\n");
for (i=0;
i<
size;
++i)printf("%d\n", arr[i]);
}
输出:
printing sorted elements 11222341023100
Java程序
#include<
stdio.h>
int temp;
void heapify(int arr[], int size, int i){int largest = i;
int left = 2*i + 1;
int right = 2*i + 2;
if (left <
size &
&
arr[left] >
arr[largest])largest = left;
if (right <
size &
&
arr[right] >
arr[largest])largest = right;
if (largest != i){temp = arr[i];
arr[i]= arr[largest];
arr[largest] = temp;
heapify(arr, size, largest);
}}void heapSort(int arr[], int size){int i;
for (i = size / 2 - 1;
i >
= 0;
i--)heapify(arr, size, i);
for (i=size-1;
i>
=0;
i--){temp = arr[0];
arr[0]= arr[i];
arr[i] = temp;
heapify(arr, i, 0);
}}void main(){int arr[] = {1, 10, 2, 3, 4, 1, 2, 100, 23, 2};
int i;
int size = sizeof(arr)/sizeof(arr[0]);
heapSort(arr, size);
printf("printing sorted elements\n");
for (i=0;
i<
size;
++i)printf("%d\n", arr[i]);
}
输出:
printing sorted elements 11222341023100
C#程序
using System;
public class HeapSorting {static void heapify(int[] arr, int size, int i){int largest = i;
int left = 2*i + 1;
int right = 2*i + 2;
int temp;
if (left <
size &
&
arr[left] >
arr[largest])largest = left;
if (right <
size &
&
arr[right] >
arr[largest])largest = right;
if (largest != i){temp = arr[i];
arr[i]= arr[largest];
arr[largest] = temp;
heapify(arr, size, largest);
}}static void heapSort(int[] arr, int size){int i;
int temp;
for (i = size / 2 - 1;
i >
= 0;
i--)heapify(arr, size, i);
for (i=size-1;
i>
=0;
i--){temp = arr[0];
arr[0]= arr[i];
arr[i] = temp;
heapify(arr, i, 0);
}}public void Main(){int[] arr = {1, 10, 2, 3, 4, 1, 2, 100, 23, 2};
int i;
heapSort(arr, 10);
Console.WriteLine("printing sorted elements");
for (i=0;
i<
10;
++i)Console.WriteLine(arr[i]);
}}
输出:
printing sorted elements 11222341023100
推荐阅读
- 图论(图Graph的表示方法)
- 栈的链表实现
- 数据结构(图(Graph))
- 栈的数组实现
- 数据结构之双链表
- 深度优先搜索(DFS)算法
- 数据结构入门介绍
- 数据结构之结构体
- 数据结构(栈(stack))