我想使用計數排序在 C 中列印一個排序陣列,但我的代碼不起作用!我觀看了計數排序演算法的教程并從視頻中復制了代碼,但由于某種原因,當代碼在視頻中運行時,我的代碼無法正常作業。我還根據部分代碼在此腳本中所做的作業撰寫了注釋。輸出應該是給定的陣列和下一行的排序陣列
#include<stdio.h>
#include<limits.h>
#include<stdlib.h>
void displayArray(int *arr,int size){
printf("[ ");
for(int i=0; i<size; i ){
printf("%d ",arr[i]);
}
printf("]\n");
}
int maximum(int A[], int size){
int max = INT_MIN;
for(int i=0; i<size; i ){
if(max < A[i]){
max = A[i];
}
}
return max;
}
void countSort(int* A, int size){
int i,j;
// Find the maximum element in Array
int max = maximum(A,size);
// Create the count array
int* count = (int*) malloc((max 1)*sizeof(int));
// Initialize the count array elements to zero
for(i=0; i < size 1; i ){
count[i] = 0;
}
// Increment the corrosponding index in the count array
for(i=0; i<size; i ){
count[A[i]] = count[A[i]] 1;
}
i = 0; // Counter for count array
j = 0; // Counter for given array
while(i <= max){
if(count[i] > 0){
A[j] = i;
count[i] = count[i] - 1;
j ;
}
else{
i ;
}
}
}
int main(){
int A[] = {56,23,53,13,64,34};
int n = 6;
displayArray(A,n);
countSort(A,n);
displayArray(A,n);
return 0;
}
uj5u.com熱心網友回復:
這個回圈
// Initialize the count array elements to zero
for(i=0; i < size 1; i ){
count[i] = 0;
}
不會將動態分配的陣列的所有元素都設定為零。
看來你的意思
// Initialize the count array elements to zero
for(i=0; i < max 1; i ){
count[i] = 0;
}
或者如果要包含標題,<string.h>
那么你可以寫
memset( count, 0, ( max 1 ) * sizeof( int ) );
或者您可以使用標準函式calloc
而不是malloc
.
請注意,如果陣列包含負數,則代碼將不起作用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/506988.html
上一篇:如何重新格式化resolve/promise.all的輸出?
下一篇:C++ 指標與一維陣列名