常见排序法

Posted on 2006-11-10 23:03 黑夜ちつ独行者 阅读(410) 评论(0)  编辑  收藏

常见排序法:

public class Sort{
   public static int count=0;

   public boolean LT(int num1,int num2){
      return num1<num2;
   }
   public void output(int[] array){
      System.out.print("第"+count+"次排序:");
      for(int i=0;i<array.length;i++)
      System.out.print(array[i]+"    ");
      System.out.println();
   }

   //冒泡排序法
   public void BubbleSort(int[] array){
      boolean swap=true;
      int index=0;

      int i=0;
      while(i<array.length-1){
         int temp=array[i];
         for(int j=i;j<array.length;j++){
            if(!LT(array[i],array[j])){
            int temp2=array[i];
            array[i]=array[j];
            array[j]=temp2;
            swap=true;
            index=j;
            }else{
            swap=false;
            }
         }
         i++;
         if(swap){
         array[i]=array[index];
         array[index]=temp;
         i++;
         }
   output(array);
   }
   }


//直接插入排序法
public void InsertSort(int[] array){
   for(int i=1;i<array.length;++i){
      if (LT(array[i],array[i-1])){
         int temp=array[i];
         array[i]=array[i-1];
         array[i-1]=temp;
         for(int j=i-1;j>0;--j){
            if(LT(array[j],array[j-1])){
               array[j]=array[j-1];
               array[j-1]=temp;
            }else{
                  break;
                    }
         }
   output(array);
   }
}
}


//快速排序法
private int Partition(int array[],int low,int high){
   int temp=array[low];
   int pivotkey=array[low];

   while(low<high){
      while(low<high&&array[high]>pivotkey) --high;
      array[low]=array[high];
      while(low<high&&array[low]<=pivotkey) ++low;
      array[high]=array[low];
   }
   array[low]=temp;
   output(array);
   return low;
}


public void QSort(int array[],int low,int high){
   if(low<high){
      int pivotloc=Partition(array,low,high);
      QSort(array,low,pivotloc-1);
      QSort(array,pivotloc+1,high);
   }
}


void QuickSort(int array[]){
   QSort(array,0,array.length-1);
}

public static void main(String args[]){
   int array[]={49,38,65,97,76,13,27,49};
   Sort sort=new Sort();

   System.out.println("===================================");
   sort.output(array);
   System.out.println("优化冒泡排序法");
   sort.BubbleSort(array);

   System.out.println();
   System.out.println("===================================");
   array=new int[]{49,38,65,97,76,13,27,49};
   sort.output(array);
   System.out.println("直接插入排序法");
   sort.InsertSort(array);

   System.out.println();
   System.out.println("===================================");
   array=new int[]{49,38,65,97,76,13,27,49};
   sort.output(array);
   System.out.println("快速排序法");
   sort.QuickSort(array);
}
}

 


只有注册用户登录后才能发表评论。


网站导航: