【发布时间】:2021-09-11 00:20:42
【问题描述】:
这是一个 bin 排序程序。我在网上找到了其他方法,但我的导师是这样认为的。我是编程初学者,请帮我写代码。
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
struct Node{
int data;
struct Node *next;
};
//Print array function
void printArray(int arr[], int n){
for(int i=0; i<n; i++)
printf("%d ",arr[i]);
printf("\n");
}
//findMax function for count and bin/bucket sort
int findMax(int arr[], int n){
int max = INT_MIN;
for(int i=0; i<n; i++){
if(arr[i]>max) max=arr[i];
}
return max;
}
//insert function for bins sort
void Insert(struct Node *Bins[], int index){
struct Node *t;
t=(struct Node*)malloc(sizeof(struct Node));
t->data = index;
t->next=NULL;
if(Bins[index] != NULL){
while(Bins[index] == NULL)
Bins[index]= Bins[index]->next;
Bins[index]->next = t;
}
else
Bins[index] = t;
}
//delete function for bin/bucket sort
int Delete(struct Node *Bins[], int i){
int x;
if(Bins[i]->next !=NULL){
struct Node *temp;
temp=(struct Node*)malloc(sizeof(struct Node));
temp=Bins[i]->next;
x=Bins[i]->data;
free(Bins[i]);
Bins[i] = temp;
}
else{
x = Bins[i]->data;
free(Bins[i]);
}
return x;
}
// bin/bucket sort
void BinSort(int arr[], int n){
int max, i, j;
struct Node **Bins;
Bins =(struct Node**)malloc(sizeof(struct Node*));
max = findMax(arr, n);
for(i =0; i<max+1; i++)
Bins[i] = NULL;
for(i=0; i<n; i++)
Insert(Bins, arr[i]);
i=j=0;
while(i < max+1){
while(Bins[i] != NULL)
arr[j++] = Delete(Bins, i);
i++;
}
}
int main(){
int n=10;
int arr[] = {8,5,7,5,3,2,6,4,11,5};
BinSort(arr, n);
printArray(arr, n);
return 0;
}
程序使用辅助数组来维护元素的计数,但使用链表,我已经编写了相应的插入和删除函数。
【问题讨论】:
-
你在做
temp=(struct Node*)malloc(sizeof(struct Node)); temp=Bins[i]->next;,所以第二行是trashing你刚刚从malloc得到的指针。可能不是你想要的并且是内存泄漏。 -
没有断言。你怎么会得到一个断言错误?
-
我认为他们有一个已在内部断言的调试分配器......但我确实希望他们粘贴了错误消息,而不是仅仅暗示它。跨度>
-
缩进不好/有误导性。清理干净。