鍊錶的歸併排序

2021-07-27 10:35:46 字數 1256 閱讀 3826

歸併排序,是一種效率較高的排序,和快速排序、希爾排序、堆排序等時間複雜度一樣為o(nlog n),且它是一種穩定的排序。

大體思想是先歸,把資料分組,比較之後再並。這種重複的分、和,十分適用遞迴的思想。

例子,4,3,6,2,8,3,0

1. 將4,3,6,2分為一組,8,3,0分為一組

2.繼續分4,3   ;   6,2      ;      8,3     ;      0

3.繼續分4 ; 3 ;   6 ;  2   ;      8 ;   3 ;      0

3,有序合併    3,4   ;   2,6      ;      3,8     ;      0

4.合併    2,3,4,6            ;      0,3,8

5.合併0,2,3,3,4,6,8

大致的過程就是這樣。

在很多筆試考試題中,有要求用鍊錶實現歸併排序。

其實也差不多。

#includeusing namespace std; 

class listnode

};

listnode *get(listnode *head,int i)

int len(listnode *head)

return len;

}void print_node(listnode *head)

cout l2->val)

else

listnode *re=result;

while(l1!=null && l2!=null)

else

}if(l1==null)

re->next=l2;

else

re->next=l1;

return result;

}

listnode *mergesort(listnode *head,int start,int end,listnode *result)

listnode *sortlist(listnode *head)

int main() ;

listnode *l1,*p;

l1=new listnode(a[0]);

p=l1;

for(int i=1;i<(sizeof(a)/sizeof(int));i++)

listnode *result=sortlist(l1);

print_node(result);

}

鍊錶歸併排序

include include include include include using namespace std typedef int type typedef struct nodetag node node build type a,int n pnode pnext null retu...

鍊錶歸併排序

主要思路 1 如果為null或者只有乙個節點那麼直接返回 2 將鍊錶分成兩部分,分別進行排序,形成兩個有序鍊錶 3 將兩個有序鍊錶合併 void merge sort struct node list void split struct node head,struct node lista,str...

鍊錶 歸併排序

時間複雜度o nlogn 空間複雜度o 1 include include 定義鍊錶 typedef struct listnode linklist linklist head null 建立鍊錶 linklist createlist int arr,int len rear next null...