我在思考计数排序以及我们如何实现它,实际上就是算法的工作方式。我困在其中的一个部分,算法实际上非常简单易懂,但其中一部分似乎并不必要。我认为人们可能会犯错,但似乎每个人都使用相同的方法,所以我可能哪里弄错了。你能解释一下吗?
以下是来自geeksforgeeks的计数排序代码。
很棒,但是关于这一部分:
注:该文本已被翻译,按原样返回即可。
那么这个部分会执行以下操作:
以下是来自geeksforgeeks的计数排序代码。
// C Program for counting sort
#include <stdio.h>
#include <string.h>
#define RANGE 255
// The main function that sort the given string arr[] in
// alphabatical order
void countSort(char arr[])
{
// The output character array that will have sorted arr
char output[strlen(arr)];
// Create a count array to store count of inidividul
// characters and initialize count array as 0
int count[RANGE + 1], i;
memset(count, 0, sizeof(count));
// Store count of each character
for(i = 0; arr[i]; ++i)
++count[arr[i]];
// Change count[i] so that count[i] now contains actual
// position of this character in output array
for (i = 1; i <= RANGE; ++i)
count[i] += count[i-1];
// Build the output character array
for (i = 0; arr[i]; ++i)
{
output[count[arr[i]]-1] = arr[i];
--count[arr[i]];
}
// Copy the output array to arr, so that arr now
// contains sorted characters
for (i = 0; arr[i]; ++i)
arr[i] = output[i];
}
// Driver program to test above function
int main()
{
char arr[] = "geeksforgeeks";//"applepp";
countSort(arr);
printf("Sorted character array is %s\n", arr);
return 0;
}
很棒,但是关于这一部分:
// Build the output character array
for (i = 0; arr[i]; ++i)
{
output[count[arr[i]]-1] = arr[i];
--count[arr[i]];
}
为什么我需要这个?好的,我数了一下我的数字:
假设我有一个数组 -> [1, 3, 6, 3, 2, 4]
注:该文本已被翻译,按原样返回即可。
INDEXES 0 1 2 3 4 5 6
I created this -> [0, 1, 1, 2, 1, 0, 1]
那么这个部分会执行以下操作:
[0, 1+0, 1+1, 2+2, 4+1, 0+5, 1+5]
[0, 1, 2, 4, 5, 5, 6]
为什么?
我不能像之前那样使用我的数组吗?这是我的想法和代码,请解释为什么它是错误的,或者为什么其他方法更有用。
void countingSort (int *arr) {
int countingArray[MAX_NUM] = {0};
for (i = 0 ; i < ARRAY_SIZE ; i++)
countingArray[arr[i]]++;
int output_Index = 0;
for (i = 0 ; i < MAX_NUM ; i++)
while ( countingArray[i]-- )
arr[output_Index++] = i;
}
memset
? - Mooing Duckwhile ( countingArray[i]-- ) arr[output_Index++] = i;
可以被替换为单个memset
调用。 - Mooing Duck