中国教程网论坛's Archiver

jiezi 发表于 2008-6-15 12:39

Shell排序算法

class ArrayShell
{
private long [] theArray;
private int nElems;
public ArrayShell(int max)
{
  theArray = new long[max];
  nElems = 0;
}
public void insert(long value)
{
  theArray[nElems] = value;
  nElems++;
}
public void display()
{
  for(int i=0;i  {
   System.out.println("theArray[" + i + "]=" + theArray[i]);
  }
}
public void shellSort()
{
  int inner,outer;
  long temp;
  int h = 1;
  while(h<=nElems/3)
      h = h*3 + 1;
  while(h>0)
  {
   for(outer=h;outer   {
    inner = outer;
    temp = theArray[outer];
    while(inner>h-1&&theArray[inner-h]>=temp)
    {
     theArray[inner] = theArray[inner-h];
     inner -= h;
    }
    theArray[inner] = temp;
   }
    h = (h-1)/3;
  }
}
}
public class ShellSortApp {

/**
  * Method main
  *
  *
  * @param args
  *
  */
public static void main(String[] args) {
  // TODO: Add your code here
  int maxSize = 10;
  ArrayShell as = new ArrayShell(maxSize);
  for(int i=0;i  {
   long n = (int)(java.lang.Math.random()*99);
   as.insert(n);
  }
  System.out.println("随机产生的数组元素:");
  as.display();
  System.out.println("使用shell算法排序:");
  as.shellSort();
  as.display();   
}
}

页: [1]

Powered by Discuz! Archiver 6.1.0  © 2001-2007 Comsenz Inc.