【算法学习】排序算法-合并排序

思想:

将有序表合并为一个大的有序表,有序表的规模一次为1,2,4,...

C代码

#include "stdio.h"
#include "stdlib.h"
void array_print(int a[],int n );
void sort_merge(int a[],int n);
int merge(int a[],int temp[],int start,int len,int n);
void main(){
	int a[]={3,1,18,30,12,11,18,43,-1,-2,-100};
	int n = sizeof(a)/sizeof(int);
	sort_merge(a,n);
	array_print(a,n);
}
void sort_merge(int a[],int n){
	//merge sort use extra memory of same size for sorting 
	// make the size of merging double times
	int *temp = (int*)malloc(n*sizeof(int));
	int len = 1;
	int i ;
	while(len <= n){
		i=0;
		while(i<n)
		  	i = merge(a,temp,i,len,n);
		len *=2;
	}
	free(temp);
}
int merge(int a[],int temp[],int start,int len,int n){
	int s1,e1,s2,e2,size_this_compare,i;
	s1 = start;
	e1 = start + len -1 ;
	if( e1 >= n-1 )
		return n;
	s2 = e1 + 1;
	e2 = s2+len-1 < n-1 ? s2+len-1 :n-1;
	size_this_compare = e2 - s1 +1;

	i=start;
	while( s1<=e1 && s2<=e2){
		while(s1<=e1 && a[s1]<=a[s2])
			temp[i++] = a[s1++];
		while(s2<=e2 && a[s2]<=a[s1])
			temp[i++] = a[s2++];
	}
	while(s1<=e1) temp[i++] = a[s1++];
	while(s2<=e2) temp[i++] = a[s2++];
	
	while(i>=start){
		i--;
		a[i]=temp[i];
	}
		
	return e2+1;
}
void array_print(int a[],int n ){
	int i;
	for(i=0;i<n;i++)
		printf("%d ",a[i]);
	printf("\n");
}


Java代码

import java.util.ArrayList;
import java.util.List;

public class SortMerge implements Sort {

	@Override
	public void sort(List<Integer> source) {
		int len =1;
		int n = source.size();
		while(len < n){
			int s1,e1,s2,e2;
			e2=-1;
			while(true){
				s1 = e2+1;
				e1 = s1+len-1;
				if(e1 >= n-1) break;
				s2 = e1+1;
				e2 = s2+len-1 < n-1 ? s2+len-1 : n-1;
				merge(source, s1, e1, s2, e2);
			}
			len *=2;
		}
	}
	private void merge(List<Integer> source , int s1, int e1, int s2,int e2){
		int t1=s1,t2=s2,i=0;
		List<Integer> temp = new ArrayList<>();
		while( t1<=e1 && t2<=e2){
			while(t1<=e1 && source.get(t1)<=source.get(t2) ) {
				temp.add(source.get(t1));
				i++;
				t1++;
			}
			while(t2<=e2 && source.get(t2)<=source.get(t1)){
				temp.add(source.get(t2));
				i++;
				t2++;
			}
		}
		while(t1<=e1){
			temp.add(source.get(t1));
			i++;
			t1++;
		}
		while(t2<=e2){
			temp.add(source.get(t2));
			i++;
			t2++;
		}
		i--;
		while(i>=0){
			source.set(e2, temp.get(i));
			i--;
			e2--;
		}
	}
	
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值