0

我正在尝试提出一种基本的基数排序(我从未真正见过,所以如果我的很糟糕,我很抱歉),但我EXC_BAD_ACCESS在线上遇到了一个错误link = *(link.pointer);。我的C技能不是很好,所以希望有人能教我我做错了什么。

我正在使用 XCode 并且启用了 ARC。

这是代码:

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>

#define ARRAY_COUNT 10
#define MAX_VALUE   1000000
#define MODULO 10.0f

typedef enum
{
    false,
    true
} bool;

typedef struct linkedListStruct
{
    int value;
    struct linkedListStruct *pointer;
} LinkedList;

void radixSort(int *array);
bool arraySorted(int *array);
int * intArray(int minValue, int maxValue);

int main(int argc, const char * argv[])
{
    int *sortingArray = intArray(0, MAX_VALUE);

    radixSort(sortingArray);

    printf("Array %s sorted", arraySorted(sortingArray) ? "" : "not");

    return 0;
}

void radixSort(int *array)
{
    int numberOfIterations = (int)ceilf(log(MAX_VALUE)/log(MODULO));
    for(int n = 0; n < numberOfIterations; n++)
    {
        LinkedList *linkedListPointers[(int)MODULO] = {0};
        int i = ARRAY_COUNT;
        while(i--)
        {
            int location = (int)floor((array[i] % (int)powf(MODULO, n + 1))/powf(MODULO, n));
            LinkedList link = { array[i], NULL };
            link.pointer = linkedListPointers[location];
            linkedListPointers[location] = &link;
        }
        int location = 0;
        for(int pointerSelection = 0; pointerSelection < MODULO; pointerSelection++)
        {
            if(linkedListPointers[pointerSelection])
            {
                LinkedList link = { 0, linkedListPointers[pointerSelection] };
                linkedListPointers[pointerSelection] = NULL;
                while(link.pointer)
                {
                    link = *(link.pointer);
                    array[location++] = link.value;
                }
            }
        }
    }
}

bool arraySorted(int *array)
{
    int i = ARRAY_COUNT;
    while(--i)if(array[i - 1] > array[i])break;
    return !i;
}

int * intArray(int minValue, int maxValue)
{
    int difference = maxValue - minValue;
    int *array = (int *)malloc(sizeof(int) * ARRAY_COUNT);
    int i;
    for(i = 0; i < ARRAY_COUNT; i++)
    {
        array[i] = rand()%difference + minValue;
    }
    return array;
}

此外,如果有人想对我的排序提出改进建议,那也将不胜感激。

4

1 回答 1

0

问题来自我如何分配链表。我变了

LinkedList link = { array[i], NULL };
link.pointer = linkedListPointers[location];

LinkedList *link = malloc(sizeof(LinkedList));
link->value = array[i];
link->pointer = linkedListPointers[location];

在第一个示例中,指向的指针在link每次循环迭代中都保持不变(我不知道它会这样做),因此我需要使指针指向新分配的内存块。

编辑:

改变也让我改变

while(link.pointer)
{
    link = *(link.pointer);
    array[location++] = link.value;
}

while(linkPointer)
{
    link = *linkPointer;
    array[location++] = link.value;
    linkPointer = link.pointer;
}
于 2013-08-01T21:51:16.727 回答