简体   繁体   中英

Time complexity of this mergesort algorithm for linkedlists

I've run this algorithm and I know that it works but I'm not too sure about its worst case time complexity. I think that the worst case time complexity for this mergesort algorithm is O(n log n). I would be thankful for anyone that can provide a second opinion.

//The main function 
public Node mergeSort(Node a){
    Node oldHead = a;
    int mid = length(a)/2;

    if(a == null || a.next == null)
        return a;

    while(mid-1 > 0){
        oldHead = oldHead.next;
        mid--;
    }
    Node newHead = oldHead.next;

    oldHead.next = null;
    oldHead = a;

    Node t1 = mergeSort(oldHead);
    Node t2 = mergeSort(newHead);

    return merge(t1,t2);
}


public Node merge(Node a, Node b){
    Node result = head;

    if(a == null)
        return b;

    if(b == null)
        return a;

    if(b.name.compareTo(a.name) <= 0){
        result = b;
        result.next = merge(a,b.next);
    }
    else{
        result = a;
        result.next = merge(a.next,b);
    }           
    return result;
}


public int length(Node a){
    int count = 0;
    Node c = a;
    while( c != null){
        count++;
        c = c.next;
    }
    return count;
}

Yes this is still O(n log(n)). Nothing is changed here from the traditional Merge sort algorithm to alter it's time complexity. The only real difference with linked lists is splitting the list in two. This has complexity of O(n) but it is at the same level as the merge operation which also has complexity O(n). So it has no overall effect on the complexity.

edit. The length operation is O(n) but again it is at the same level as the split operation and the merge operation, which are also O(n) so it too doesn't effect the time complexity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM