【算法学习】排序算法-合并排序
来源:互联网 发布:javascript java 编辑:程序博客网 时间:2024/06/05 07:33
思想:
将有序表合并为一个大的有序表,有序表的规模一次为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 timesint *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 {@Overridepublic 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--;}}}
0 0
- 【算法学习】排序算法-合并排序
- 排序算法---合并排序
- 排序算法-合并排序
- 算法学习之排序(6)--合并排序
- 算法学习之合并排序算法
- 排序算法之合并排序
- 简单排序算法:合并排序
- 排序算法(二):合并排序
- 排序算法之合并排序
- 排序算法之合并排序
- 排序算法·合并排序
- 合并排序算法
- 合并排序算法
- 算法-----合并排序
- java 合并排序算法
- 合并排序算法
- 合并排序算法
- 合并排序算法
- Unity新UI系统概述——Animation Integration
- source insight使用技巧
- bzoj1007: [HNOI2008]水平可见直线 凸包
- uva 10602
- JSP详细篇——Servlet监听器
- 【算法学习】排序算法-合并排序
- 基于PHP的一种Cache回调与自动触发技术
- js提交表单
- UVA 10714
- 黑马程序员——学习笔记——泛型
- UVA 10718
- Unity学习小结5 - 利用BMFont制作美术字及要点注意
- UVA 311
- UVA 10487