### [算法]——归并排序（Merge Sort）

```// A structure data definition
typedef struct __Student
{
char name[16];
int score;
}Student;
// Array of students
name :  A      B     C     D
score:  80     70    75    70

Stable sort in ascending order:
name :  B      D     C     A
score:  70     70    75    80

Unstable sort in ascending order:
name :  D      B     C     A
score:  70     70    75    80
```

1)数组的归并排序

```// Split arr[] into two parts [begin,mid), [mid,end)
// and using merge_core to merge this two parts
// Total Time O(nlogn)
void merge_sort(int arr[], int begin, int end)
{
if (end-begin < 2) return;
int mid = (begin+end)>>1;
merge_sort(arr,begin,mid);
merge_sort(arr,mid,end);
merge_core(arr,begin,mid,end);
}	// Time O(logn)
```

```/* merge core: combine two parts which are sorted in ascending order
* arr[]: ..., 1, 4, 8, 2, 3, 7, 9, ...
*      begin__|        |__mid      |__end
* part1: 1, 4, 8       part2: 2, 3, 7, 9
*
* combination:
* part1:[1]            [4]       [8]
* part2: |   [2]  [3]   |   [7]   |   [9]
*        |    |    |    |    |    |    |
* tmp  :[1]  [2]  [3]  [4]  [7]  [8]  [9]
*
* at last, copyback tmp to arr[begin,end)
* */
```

```void merge_core(int arr[], int begin, int mid, int end)
{
int i=begin, j=mid, k=0;
int *tmp = (int*)malloc(sizeof(int)*(end-begin));
for(; i<mid && j<end; tmp[k++]=(arr[i]<arr[j]?arr[i++]:arr[j++]));
for(; i<mid; tmp[k++]=arr[i++]);
for(; j<end; tmp[k++]=arr[j++]);
for(i=begin, k=0; i<end; arr[i++]=tmp[k++]);
free(tmp);
}	// Time O(n), Space O(n)
```

2)链表的归并排序

```// Merge sort for single list as ascending order
// single list node define
typedef struct __ListNode
{
int val;
struct __ListNode *next;
}ListNode;

// Merge sort for single list without head node
{
ListNode *fast, *mid, H;
// find mid node between head and end
for (H.next=head, fast=mid=&H; fast && fast->next;){
mid = mid->next;
fast = fast->next->next;
}
fast = mid->next;
mid->next = NULL;	// cut down mid part from head list
mid = fast;

mid = merge_sort(mid);
}
```

```// merge single list without head node (ascending order)
ListNode *merge_core(ListNode *i, ListNode *j)
{
ListNode H, *p;
for (p=&H; i && j; p=p->next){
if (i->val < j->val){
p->next = i;
i = i->next;
}
else{
p->next = j;
j = j->next;
}
}
p->next = (i ? i:j);
return H.next;
}
```

注：本文涉及的源码：merge sort : https://git.oschina.net/eudiwffe/codingstudy/blob/master/src/sort/mergesort.c