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

冒泡排序

//时间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;
  }
  
 }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值