Created
October 20, 2014 13:42
-
-
Save rickyzhang-cn/4b83551285af48ed161f to your computer and use it in GitHub Desktop.
排序算法的C实现
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| void merge(int a[], int temp_array[], int l_pos, int r_pos, int end) | |
| { | |
| int i=0; | |
| int j; | |
| int l=l_pos,r=r_pos; | |
| while(l<r_pos && r<=end) | |
| { | |
| while(a[l]<a[r]) | |
| temp_array[i++]=a[l++]; | |
| while(a[r]<a[l]) | |
| temp_array[i++]=a[r++]; | |
| } | |
| if(l<r_pos-1) | |
| { | |
| for(j=l;j<r_pos;j++) | |
| temp_array[i]=a[j]; | |
| } | |
| if(r<end) | |
| { | |
| for(j=r;j<=end;j++) | |
| temp_array[i]=a[j]; | |
| } | |
| for(i=0,j=l_pos;j<=end;i++,j++) | |
| a[j]=temp_array[i]; | |
| } | |
| void m_sort(int a[], int temp_array[], int left, int right) | |
| { | |
| int center; | |
| if(left<right) | |
| { | |
| center=(left+right)/2; | |
| m_sort(a,temp_array,left,center); | |
| m_sort(a,temp_array,center+1,right); | |
| merge(a,temp_array,left,center+1,right); | |
| } | |
| } | |
| void merge_sort(int a[], int n) | |
| { | |
| int* temp_array; | |
| temp_array=(int *)malloc(n*sizeof(int)); | |
| if(temp_array==NULL) | |
| { | |
| printf("fail to malloc\n"); | |
| exit(1); | |
| } | |
| m_sort(a,temp_array,0,n-1); | |
| } | |
| int main(void) | |
| { | |
| int i; | |
| int a[10]={10,9,8,7,6,5,4,3,2,1}; | |
| merge_sort(a,10); | |
| for(i=0;i<10;i++) | |
| { | |
| printf("%d\t",a[i]); | |
| } | |
| printf("\n"); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment