在上一篇 C++、C#、java算法学习日记05 中由于电脑出了点问题java启动不了,这一篇我补上:
希尔排序java实例:
package Sort;
import java.util.*;
public class Sort5 {
public void ShellSort(List<Integer> array){
int Length=array.size();//获取长度
int step=Length/2;
int temp,i,j;
long time_start=System.currentTimeMillis();//开始时间
while(step>=1){
for(i=step;i<Length;i++){
temp=array.get(i);
for(j=i-step;j>=0&&temp<array.get(j);j=j-step){
array.set(j+step,array.get(j));
}
array.set(j+step,temp);
}
step=step/2;
}
long time_stop=System.currentTimeMillis();//结束时间
System.out.println("前十位元素为:");
//输出
for(i=0;i<10;i++){
System.out.print(array.get(i)+" ");
}
System.out.println();
System.out.print("希尔排序用时:"+(time_stop-time_start)+"毫秒");
}
public static void main(String[] args) {
//List接口由ArrayList实现
List<Integer> array = new ArrayList<Integer>();
//产生10000个随机数
for(int i=1;i<10000;i++){
array.add(new Random().nextInt(100000));
}
Sort5 sorter = new Sort5();
//希尔排序
sorter.ShellSort(array);
}
}
结果:
还有在上一篇当中C#的实例代码中有一个错误,int Length = array.Count/2; (我当时就好奇了,怎么结果用时这么短,原来少排了一半啊)改为int Length = array.Count;就行了,用时结果与C++的差不多了