c - 如何将插入排序转换为 O(n logn) 算法?

标签 c algorithm sorting insertion-sort

我编写了以下函数,该函数在创建排序的字符串序列时对字符串的重复实例进行计数。然而速度很慢,然后我意识到这是 O(n^2)。所以我想让它变成 O(n logn) 但我不知道如何继续。是否有任何已知的方法可以将此类 n^2 算法转换为 nlogn?该如何转换呢?

void insert (struct listNode **ptr, char *value) {
    struct listNode *newPtr;
    int cmp;

    // find a place to instert node to LL
    while(*ptr){
        // Comparision to detect & remove duplicates nodes

        cmp = strcmp(value, (*ptr)->data);
        // duplicate
        if(cmp == 0){
            (*ptr)->occurrence++;
            return; 
        }
        // the point where i need to add the node
        if(cmp < 0) 
            break;

        ptr = &(*ptr)->next;
    }

    // now here *ptr points to the pointer that i want to change
    // it can be NULL, if we are at the end of the LL

    newPtr = malloc(sizeof *newPtr);
    if(!newPtr)
        return;

    newPtr->data = strdup(value);
    newPtr->occurrence = 1;

    if(newPtr->data == NULL){
        free(newPtr);
        return;     
    }

    // here we are connecting our brand new node to the LL
    newPtr->next = *ptr;
    *ptr = newPtr;
}

struct listNode {
    char *data;
    struct listNode *next;
    int occurrence;
};

最佳答案

Are there any known methods for converting such n2 algorithm to n*logn?

当您相乘的两个 n 之一来自访问线性数据结构(例如链表)时,您可以改进为 n*log n 通过转向更快的数据结构,例如平衡二叉树。

这将意味着将线性的 while 循环搜索替换为二叉树中的搜索(logn)。

关于c - 如何将插入排序转换为 O(n logn) 算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29493030/

相关文章:

c++ - 找到气体容器的最小必要体积

java - 当我进入 JFrame 时如何对 JTable 的列进行排序?

c - 预期的主要错误总是出现在 c 中

python - 数组中数字的绝对差之和

c - 堆化时出现段错误

algorithm - 如何制作GPS交通应用程序?

java - 对任何类型的对象进行排序,java

java - 如何在 java 中为 ArrayList 中的数据指定排序顺序?

c - 在 C 中读/写结构到 fifo

c - 与 Active Directory 的 SSO 握手