归并排序的简单实现

#include <stdio.h>
#include <stdlib.h>

int arr[] = {8, 4, 5, 7, 1, 3, 6, 2,9};
int a[] = {8, 4, 5, 7, 1, 3, 6, 2,9};
void GuiBingSort(int start ,int end){//0~n-1
	//不可再分则退出 
	if(end - start < 1) return;
	//二分 
	int mid = start+(end - start)/2;
	//二分后的两个数组,再次进行递归 
	GuiBingSort(start,mid);
	GuiBingSort(mid + 1,end);
	
	//当两个数组都按顺序排好后 
	int s = start;//第一个数组头 
	int b = mid+1;//第二个数组头 
	int i = start;//排序结果放i里 
	
	while(s<=mid && b<=end){//哪个小,往a里放哪个 
		if(arr[s]<=arr[b]){
			a[i++]=arr[s++];
		}
		else{
			a[i++]=arr[b++];
		}
	}
	
	while(s<=mid)
		a[i++] = arr[s++];
		
	while(b<=end)
		a[i++] = arr[b++];
	//防止有一个数组没有遍历完 
	
	
	for(i = start;i<=end;i++){
		arr[i] = a[i];
	}
	//把排好的数组内容,从临时数组放到大数组里 
} 

int main() {
	int size = sizeof(arr)/4;
    GuiBingSort(0,size-1);
    for (int i = 0; i < size ;i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    return 0;
}

posted @ 2025-03-20 15:38  嘉君  阅读(253)  评论(0)    收藏  举报