c - 这个算法的时间复杂度是多少。我可以让它更快吗?

标签 c algorithm sorting quicksort timsort

该算法在从 arrl 开始到 depr 结束的特定时间间隔内找到最重叠的事件(带)。我使用快速排序实现 O(nlogn) 时间复杂度,然后使用 O(n) 的 while 循环来计算在这些时间间隔内进行相互冲突的事件 1.这是否像 O(nlogn) + O(n) 时间复杂度? 2.我可以在 O(n) 时让它更快吗? 3.最后,理论上,O(n)时间复杂度是否可以使用Timsort?

用 C 编写的代码用于 15 个事件,但假设它是通用的并且具有未排序的 arrl 和 depr

编辑:结果是 1 小时内事件最多

void findMaxBands(int n,int arr1[n],int depr[n]);
void quickSort(int a[],int l,int h);
int partition(int a[],int l,int h);

int main(){
    int arrl[15] = {18,18,19,19,19,19,20,20,20,20,21,22,22,22,23};
    int depr[15] = {19,21,20,21,22,23,21,22,22,23,23,23,24,24,24};
    int n = 15;
    findMaxBands(n,arrl,depr);
    return 0;
}

void findMaxBands(int n,int arrl[n],int depr[n]){
    quickSort(arrl,0,15);
    quickSort(depr,0,15);

    int guestsIn = 1,maxGuests = 1,time = arrl[0];
    int i = 1, j = 0;

    while (i < n && j < n){
        if (arrl[i] <= depr[j]){
            guestsIn++;
            if (guestsIn > maxGuests){
                maxGuests = guestsIn;
                time = arrl[i];
            }
            i++;
        }
        else{
            guestsIn--;
            j++;
        }
    }
    printf("Maximum Number of Bands : %d at time %d-%d",maxGuests,time-1,time);
}

void quickSort(int a[],int l,int h){
    int j;
    if(l<h){
        j=partition(a,l,h);
        quickSort(a,l,j-1);
        quickSort(a,j+1,h);
    }
}

int partition(int a[],int l,int h){
    int v,i,j,temp;
    v=a[l];
    i=l;
    j=h+1;

    do{
        do{
            i++;
        }while(a[i]<v&&i<=h);
        do{
            j--;
        }while(v<a[j]);
        if(i<j){
            temp=a[i];
            a[i]=a[j];
            a[j]=temp;
        }
    }while(i<j);
    a[l]=a[j];
    a[j]=v;
    return(j);
}

最佳答案

1.So is this like O(nlogn) + O(n) time complexity?

O(n log(n)) + O(n) = O(n log(n))

引用。例如。 Big O when adding together different routines了解更多详情。

2.Can i make it even faster at O(n)?

3.Lastly,theortically,is it possible to use Timsort for O(n) time complexity?

通用(比较)排序算法的最佳情况复杂度可能为 O(n),但平均/最坏情况的复杂度最多为 O(n log(n))。您可以找到几种排序算法的概述 here及其复杂性。

关于c - 这个算法的时间复杂度是多少。我可以让它更快吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53590368/

相关文章:

c - 为什么这个数组中的第一个元素不存储任何值?

java - 优化排序方法

sorting - Groovy - 使用两个标准对我的对象列表进行排序

javascript - 在 JavaScript 中对函数数组进行排序

algorithm - 具有随机 1bit 增益/损失的编码

c++ - 有效地交织位

c - 将FPU与C内联汇编一起使用

javascript - 网页开发 : how to access a variable from an embedded c code to javascript?

c++ - 检测可移动驱动器(例如 USB 闪存驱动器)C/C++

algorithm - 递归访问二叉树中的节点