【发布时间】:2020-03-22 07:10:29
【问题描述】:
我被要求用堆排序、冒泡排序和选择排序对 50,000 个随机整数(从 0 到 1000)进行排序,看看哪种方法最有效。我的冒泡排序和选择排序工作正常,但我注意到我的堆排序没有正确排序。我从另一个程序重新使用了我的堆排序,它在原始程序中工作,所以我很困惑为什么它在这里不起作用。然后我用一个较小的整数进行了测试,它起作用了。 我确定堆排序适用于 5760 及以下的数字,但不适用于 5761 及以上的数字,我不知道为什么..有人可以帮忙吗?
注意:排序后的数组会打印到名为“heap.txt”的项目文件夹中的 txt 文件中,输出屏幕中打印的数字是程序对数据进行排序的迭代次数。
我试图找出数字 5761 的任何数字相关性,但找不到为什么这个数字特别会破坏程序。
注意:我将只包括堆函数和主函数的那部分。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define MAX 5761 //50000 integers to sort
int heapcount = 0;
int last = MAX - 1;
void reheapUp(int heap[], int newNode);
void reheapDown(int heap[], int root, int last); //the 4 heap function declarations needed for this program.
void buildHeap(int heap[]);
int deleteHeap(int heap[], int last);
int main() {
int i;
int arraytochange[MAX];
for (i = 0; i < MAX; i++) {
arraytochange[i] = rand() % 1001; // copy the random numbers in the unchanged array
}
buildHeap(arraytochange);
printf("%d \n", heapcount); // number of iterations
char* nameoffile3 = "heap.txt"; //text file name
FILE *HeapSort; //pointer to file type
HeapSort = fopen(nameoffile3, "w+"); //opens the file in read and write mode, creates the file if it doesn't exist
if (HeapSort == NULL) {
printf("Could not open file. \n"); // if couldn't open file
system("pause");
return 0;
}
else {
printf("Heap File Opened Successfully.\n"); //print that the file opened successful
}
for (i = 0; i < MAX; i++) {
fprintf(HeapSort, "%d \n", deleteHeap(arraytochange, last));
last--;
}
fclose(HeapSort);
system("pause");
return 0;
}
void buildHeap(int heap[]) {
int walker = 1;
while (walker < MAX) {
reheapUp(heap, walker);
walker++;
}
}
void reheapUp(int heap[], int newNode) {
heapcount++;
int parent = 0;
int temp = 0;
if (newNode != 0) {
parent = ((newNode - 1) / 2);
if (heap[newNode] < heap[parent]) {
temp = heap[newNode];
heap[newNode] = heap[parent];
heap[parent] = temp;
reheapUp(heap, parent);
}
}
}
void reheapDown(int heap[], int root, int last) {
heapcount++;
int leftKey; // value of left subtree, not index
int rightKey; // value of right subtree, not index
int largeSubtree; // value not index
int temp;
int index;
if (((2 * root + 1) <= last) && (heap[2 * root + 1] > 0)) {
leftKey = heap[2 * root + 1];
if (((2 * root + 2) <= last) && (heap[2 * root + 2] > 0)) {
rightKey = heap[2 * root + 2];
}
else {
rightKey = NULL;
}
if (leftKey < rightKey) {
largeSubtree = heap[2 * root + 1];
index = (2 * root + 1);
}
else {
largeSubtree = heap[2 * root + 2];
index = (2 * root + 2);
}
if (heap[root] > largeSubtree) {
temp = heap[index];
heap[index] = heap[root];
heap[root] = temp;
reheapDown(heap, index, last);
}
}
//printf("Last: %d \n", last);
}
int deleteHeap(int heap[], int last) {
int dataOut;
dataOut = heap[0];
heap[0] = heap[last];
reheapDown(heap, 0, last);
return dataOut;
}
注意:_CRT_SECURE_NO_WARNINGS 在那里,所以我可以使用所有系统功能而不会出现警告 MAX 是一个带有随机数个数的常数。它设置在程序顶部,当前设置为 5761
【问题讨论】:
-
评论不用于扩展讨论;这个对话是moved to chat。
标签: c sorting data-structures heap heapsort