| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 676 人关注过本帖
标题:关于排序的问题
只看楼主 加入收藏
Zidane
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2006-7-20
收藏
 问题点数:0 回复次数:0 
关于排序的问题

为什么在用选择排序和归并排序对100000个数进行排序,选择排序耗时要比归并排序短,书上不是说归并排序效率更高吗?
以下是程序:
public class MySort{
public static void selectionSort(int theArray[],int size){
//选择排序
//size 数组长度
int tmp;
int index;
int n=size;
for(int i=0; i<size-1; i++,n--) {
index=indexOfLargest(theArray,n);
tmp=theArray[n-1];
theArray[n-1]=theArray[index];
theArray[index]=tmp;
}//end for
}//end selectionSort
private static int indexOfLargest(int theArray[],int size){
//查找数组中的最大项
int max=theArray[0];
int i;
int maxNum=0;
for(i=1;i<size;i++)
if (theArray[i]>max){
max=theArray[i];
maxNum=i;
}//end if
return maxNum;
}
public static void mergeSort(int[] theArray,int first,int last){ //归并排序
if(first<last){ int mid=(first+last)/2;
mergeSort(theArray,first,mid);
mergeSort(theArray,mid+1,last);
merge(theArray,first,mid,last);
}//end if
}//end mergeSort
public static void merge(int[] theArray,int first,int mid,int last){
int[] tmpArray=new int[theArray.length];
int first1=first;
int last1=mid;
int first2=mid+1;
int last2=last;
int index=first1;
for(;first1<=last1&&first2<=last2;){
if(theArray[first1]>theArray[first2]){
tmpArray[index]=theArray[first2];
first2++;
index++;
}
else{
tmpArray[index]=theArray[first1];
first1++;
index++;
}//end if
}//end for
for(;first1<=last1&&index<=tmpArray.length-1;first1++,index++)
tmpArray[index]=theArray[first1];
for(;first2<=last2&&index<=tmpArray.length-1;first2++,index++)
tmpArray[index]=theArray[first2];
for(int i=first;i<=last;i++)
theArray[i]=tmpArray[i];

}//end merge
}//end class


以下是测试程序:
public class SortText{
public static void main(String arg[]){
final int MAX=100000;
int a[];
a=new int[MAX];
for(int i=MAX;i>0;i--)
a[MAX-i]=i;
long time1=System.currentTimeMillis();
// MySort.selectionSort(a,MAX); //选择排序
MySort.mergeSort(a,0,MAX-1); //归并排序
long time2=System.currentTimeMillis();
System.out.println(time2-time1);
}
}

搜索更多相关主题的帖子: int theArray tmp public 数组 
2006-07-20 16:07
快速回复:关于排序的问题
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.014877 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved