2种选择排序算法的效率比较(带测试main方法)

本文介绍了一种简单但效率较低的选择排序算法实现,并提供了两种不同版本的选择排序方法。第一种直接比较并交换元素,第二种寻找子数组中最小值的位置再进行交换,后者相对更优。通过示例代码展示了如何使用这些算法来对整数数组进行排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class TestSortArgs {
 public static void print(int [] temp) {//打印数组算法
  for(int i=0;i<temp.length;i++) {
   System.out.print(" " + temp[i]);
  }
 }
 /******************************************************************/
 public static void selectSort1(int [] temp) {//选择排序算法,效率不高
  for(int i=0;i<temp.length;i++){
   for(int j=i+1;j<temp.length;j++) {
    if(temp[i]>temp[j]) {
     int in ;
     in = temp[i] ;
     temp[i] = temp[j] ;
     temp[j] = in ;
    }
   }
  }
 }
 /******************************************************************/
 public static void selectSort2(int []a) {//选择排序算法,效率较前者更好
  int k,temp ;
  for(int i=0;i<a.length;i++) {
   k = i ;
   for(int j=k+1;j<a.length;j++) {
    if(a[j] < a[k])
     k = j ;
   }
   if(k != i) {
    temp = a[i] ;
    a[i] = a[k] ;
    a[k] = temp ;
   }
  }
  
 }
 
 /******************************************************************/
 public static void main(String [] args) {
  int a[] = new int[args.length] ;
  
  for(int i=0;i<args.length;i++){
   a[i] = Integer.parseInt(args[i]) ;
  }
  
  TestSortArgs t = new TestSortArgs();
  
  System.out.print("you have input the array:");
  t.print(a);
  
  System.out.println();
  System.out.print("After selectSort the array is:");
  
  //t.selectSort1(a);//调用选择排序算法1
  t.selectSort2(a);//调用选择排序算法2
  t.print(a);
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值