堆的建立, 元素插入, 删除的实现...
2010-07-29 11:22
309 查看
#include <cstdlib> #include <iostream> #include <algorithm> #include <ctime> #include <vector> using namespace std; const int MAX = 200; void filerDown(int heap[], int start, int end) { int i = start; int j = 2 * i + 1; int temp = heap[i]; while(j < end) { if(j < end - 1 && heap[j] > heap[j + 1]) j++; if(temp < heap[j]) break; else { heap[i] = heap[j]; i = j; j = 2 * j + 1; } } heap[i] = temp; } void filerUp(int heap[], int start) { int i = start; int j = (i - 1) / 2; int temp = heap[i]; while(i > 0) { if(temp >= heap[j]) break; else { heap[i] = heap[j]; i = j; j = (j - 1) / 2; } } heap[i] = temp; } void insert(int heap[], int value, int& count) { heap[count] = value; filerUp(heap, count); count++; } void dele(int heap[], int& count) { heap[0] = heap[count - 1]; count--; filerDown(heap, 0, count - 1); } void createHeap(int heap[], int count) { int curSize = count; int curPos = (curSize - 2) / 2; while(curPos >= 0) { filerDown(heap, curPos, curSize); curPos--; } } int main(int argc, char *argv[]) { int heap[MAX]; int count = 100; vector<int> vec; srand((unsigned)time(NULL)); for(int i=0; i<count; i++) { int value = rand() % 1000; heap[i] = value; vec.push_back(value); } cout << " all elements are: " << endl; sort(vec.begin(), vec.end()); for(int i=0; i<count; i++) cout << vec.at(i) << " "; cout << endl; cout << "min element is: " << endl; createHeap(heap, count); cout << heap[0] << endl; cout << "after insert value 5" << endl; insert(heap, 5, count); cout << heap[0] << endl; cout << "after delete the min value" << endl; dele(heap, count); cout << heap[0] << endl; system("PAUSE"); return EXIT_SUCCESS; }
相关文章推荐
- 输入一组整型元素序列,使用尾插法建立一个带有头结点的单链表。 ② 实现该线性表的遍历。 ③ 在该单链表的第i个元素前插入一个整数。 ④ 删除该单链表中的第i个元素,其值通过参数将其返回。 ⑤ 建立两个
- 队列用链表实现(建立,插入新元素,删除元素,读取元素,全部删除,全部读出,判断是否为空,清空)
- (1)顺序表的操作 ① 输入一组整型元素序列,建立线性表的顺序存储结构。 ② 实现该线性表的遍历。 ③ 在该顺序表中查找某一元素,查找成功显示查找元素,否则显示查找失败。 ④ 在该顺序表中删除或插入指
- C语言单向动态链表程序,实现链表的建立,合并,重新排序,链表元素的插入与删除,以及根据元素成员的值进行元素删除。
- 队列用链表实现(建立,插入新元素,删除元素,读取元素,全部删除,全部读出,判断是否为空,清空)
- (2)单链表的操作 ① 输入一组整型元素序列,使用尾插法建立一个带有头结点的单链表。 ② 实现该线性表的遍历。 ③ 在该单链表的第i个元素前插入一个整数。 ④ 删除该单链表中的第i个元素,其值通过参数
- 实现一个单链表的建立、测长、打印、删除、插入
- 链表的基本操作(创建,查找指定位置元素,删除指定元素,插入,倒置,去重,求集合的差,分别交换结点与交换结点值实现的冒泡排序,将两个有序链表合并成一个有序链表)c语言实现
- 跨服务器视图怎么建立,要求要能实现插入修改删除
- 单链表的建立,查找,插入,删除,测长,打印,逆置操作实现
- C++实现最小堆及插入,调整顺序,删除堆顶元素的操作
- 二叉排序树的建立、插入、删除、查找、比较、4种遍历方式的C++完整实现版
- C++实现最小堆及插入,调整顺序,删除堆顶元素的操作
- BST 存储结构建立(插入)、删除、 查找算法的实现及应用
- 二叉排序树的建立、插入、删除、查找、4种遍历 C++完整实现
- 编程实现顺序表的以下基本操作:建立顺序表,修改顺序表,插入顺序表,删除顺序表。
- C++实现红黑树建立,销毁,查找,插入和删除
- c语言实现线性表的建立,初始化,插入,删除,查找,遍历以及时间复杂度分析
- C语言:动态链表的建立,查找,删除,插入功能的实现
- 实现列表类,清空、添加、删除、查找、插入,判断元素是否存在