java算法:选择排序

来源:互联网 发布:手机上能注册淘宝店铺 编辑:程序博客网 时间:2024/05/18 03:58

java算法:选择排序

选择排序:找数组中的最小元素与第一个位置的元素比较交换,然后找第二个最小的元素并与第二个位置的元素比较交换,一直进行下去,直到整个数组排序完毕。

如,对EXAMPLE 字母进行排序:

 
 E   X   A   M   P   L   E
[A]  X   E   M   P   L   E 第一位置最小值A
[A] [E]  X   M   P   L   E 第二位置剩下最小值E
[A] [E] [E]  M   P   L   X 第三位置剩下最小值E
[A] [E] [E] [L]  P   M   X ...
[A] [E] [E] [L] [M]  P   X
[A] [E] [E] [L] [M] [P]  X
[A] [E] [E] [L] [M] [P] [X]

Java代码 复制代码
  1. public interface Item{   
  2.     boolean less(Item v);   
  3. }  
Java代码 复制代码
  1. public class MyItem implements Item{   
  2.     private int key;   
  3.     public boolean less(Item v){   
  4.         return key < ((MyItem)v).key;   
  5.     }   
  6.     public void read(){   
  7.         key = new Random().nextInt();   
  8.     }   
  9.     public void rand(){   
  10.         key = (int)(1000 * Math.random());   
  11.     }   
  12.     public String toString(){   
  13.         return key + "";   
  14.     }   
  15. }  
Java代码 复制代码
  1. public class Selection {   
  2.   
  3.     public static void main(String[] args) {   
  4.         int n = 60;   
  5.         MyItem [] a = new MyItem[n];   
  6.         for (int i = 0; i < n; i++) {   
  7.             a[i] = new MyItem();   
  8.             a[i].rand();   
  9.         }   
  10.            
  11.         for (int i = 0; i < n; i++) {   
  12.             System.out.print(a[i] + " ");   
  13.         }   
  14.            
  15.         selection(a, 0, n);   
  16.         System.out.println("");   
  17.         print(a, n);   
  18.     }   
  19.        
  20.     private static void print(MyItem a [], int n){   
  21.         for (int i = 0; i < n; i++) {   
  22.             System.out.print(a[i] + " ");   
  23.         }   
  24.     }   
  25.        
  26.     public static void selection(MyItem [] a, int l, int r){   
  27.         for (int i = l; i < r; i++) {   
  28.             int min = i;   
  29.             for (int j = i + 1; j < r; j++) {   
  30.                 if(less(a[j], a[min])){   
  31.                     min = j;   
  32.                 }   
  33.             }   
  34.             exch(a, i, min);   
  35.         }   
  36.     }   
  37.        
  38.     public static boolean less(Item v, Item w){   
  39.         return v.less(w);   
  40.     }   
  41.        
  42.     public static void exch(Item [] a, int i, int j){   
  43.         Item t = a[i];   
  44.         a[i] = a[j];   
  45.         a[j] = t;   
  46.     }   
  47.        
  48.     public static void compExch(Item [] a, int i, int j){   
  49.         if(less(a[j],a[i])){   
  50.             exch(a, i, j);   
  51.         }   
  52.     }   
  53. }  

选择排序的缺点是它的运行时间与文件中已排序的数量几乎没有关系。寻找最小元素的一次遍历并不能提供多少关于下一次遍历文件时最小元素位置的信息。可以看到,使用选择排序所花费的时间不管对于随机或已排好都是差不多。不能很好的利用文件中的有序性。