您的位置:首页 > 其它

简单排序(冒泡,选择排序,插入排序)

2012-04-10 16:52 267 查看
冒泡排序

//时间2012.4.10

//功能:冒泡排序

//作者:

public class TestSort {

 /**

  * @param args

  */

 public static void main(String[] args) {

  // TODO Auto-generated method stub

  long[] arry=new long[5];

  arry[0]=35;

  arry[1]=25;

  arry[2]=45;

  arry[3]=15;

  arry[4]=55;

  for(long num:arry)

  {

  System.out.print(num+" " );

  }

  System.out.println();

  //冒泡排序

  BubbleSort.sort(arry);

  for(long num:arry)

  {

  System.out.print(num+" " );

  }

 }

}

public class BubbleSort {

 public static void sort(long[] arry)

 {  //确定第几趟排序

  for(int i=0;i<arry.length-1;i++)

  {

   //确定好当前元素,和后面元素比较(从后面开始)

   for(int j=arry.length-1;j>i;j--)

   {

    long temp=0;

    if(arry[j]<arry[j-1])

    {

     temp=arry[j];

     arry[j]=arry[j-1];

     arry[j-1]=temp;

    }

   }

   

  }

 }

}

选择排序(效率要比冒泡排序高一些,交换的次数要少)

public class StraitSsort {

 /**

  * @param args

  */

 public static void main(String[] args) {

  // TODO Auto-generated method stub

  long[] arry=new long[5];

  arry[0]=23;

  arry[1]=13;

  arry[2]=33;

  arry[3]=3;

  arry[4]=43;

  for(long num:arry)

  {

   System.out.print(num+" ");

  }

  //打印换行

  System.out.println();

  Sort.selectsort(arry);

  for(long num:arry)

  {

   System.out.print(num+" ");

  }

  

 }

}

public class Sort {

 public static void selectsort(long[] arry)

 {

  int k=0;

  long temp;

  

  //i记录趟数

  for(int i=0;i<arry.length-1;i++)

   //通过j和k,并且k指向最小数

  {

   k=i;

   for(int j=i;j<arry.length ;j++)

   {

    if(arry[j]<arry[k])

    {   

     //交换次序使k指向为最小的

                 k=j;

     

    }

    

   }

   temp=arry[i];

   arry[i]=arry[k];

   arry[k]=temp;

   

   

  }

 }

 

}

直接插入排序

public class InsertSort {

 public static void sort(long[] arry)

 {

  long temp=0;

  for(int i=1;i<arry.length;i++)

  {

   temp=arry[i];

   int j=i;

   while(j>0&&arry[j]>=temp)

   {

    arry[j]=arry[j-1];

    j--;

   }

   arry[j]=temp;

  }

  

 }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  class string