归并排序 (java版本的,自己参考的是严版的数据结构)(2011.6.21日写)

import java.util.*; public class MergeSort { /** * @param args */ static void mergeSort(int [] a,int [] temp,int left,int right) { if (left==right) temp[left]=a[left]; else { int temp2[]=new int[] {0,0,0,0,0,0,0,0,0,0}; int middle=(left+right)/2; mergeSort(a,temp2,left,middle); mergeSort(a,temp2,middle+1,right); merge(temp2,temp,left,middle,right); } } static void merge(int[] temp2,int[] temp,int left,int middle,int right) { int k,j; for(k=left,j=middle+1;left<=middle&&j<=right;++k) { if(temp2[left]<temp2[j]) temp[k]=temp2[left++]; else temp[k]=temp2[j++]; } /* if(left<=middle&&middle<=right-1) { if(temp2[left]<temp2[middle+1]) { temp[count]=temp2[left]; left++; else { temp[count]=temp2[middle+1]; middle++; } count++; }*///我错误点在于:1是middle是自己增加的,没有将j=middle+1,导致会出现问题。 //第二个问题是好多自加操作实际上是可以用left++可以放到运算的内部。 while(left<=middle) temp[k++]=temp2[left++]; while(j<=right) temp[k++]=temp2[j++]; //代码要美观,哈 } public static void main(String[] args) { // TODO Auto-generated method stub int a[]=new int[] {9,2,4,5,8,0,1,3,7,6}; for(int i=0;i<10;i++) { System.out.printf("%d ",a[i]); } int temp[]=new int[] {0,0,0,0,0,0,0,0,0,0}; mergeSort(a,temp,0,9); System.out.println("排序后的结果是"); for(int i=0;i<10;i++) { System.out.printf("%d ",temp[i]); } Scanner in =new Scanner(System.in); in.nextInt(); } }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值