JAVA排序算法之 选择排序

1. 选择排序

选择排序的基本思想是遍历数组的过程中,以i代表当前需要排序的序号,则需要在剩余的[i..n-1]中找出其中的最小值,然后将找到的最小值与i指向的值进行交换。因为每一次确定元素的过程中都会有一个选择很大值的子流程,所以称之为选择排序。

比如[38, 17, 16, 16, 7, 31, 39, 32, 2, 11]

i = 0:  [2 , 17, 16, 16, 7, 31, 39, 32, 38 , 11] (0th [38]<->8th [2])

i = 1:  [2, 7 , 16, 16, 17 , 31, 39, 32, 38, 11] (1st [38]<->4th [17])

i = 2:  [2, 7, 11 , 16, 17, 31, 39, 32, 38, 16 ] (2nd [11]<->9th [16])

i = 3:  [2, 7, 11, 16, 17, 31, 39, 32, 38, 16] ( 无需交换 )

i = 4:  [2, 7, 11, 16, 16 , 31, 39, 32, 38, 17 ] (4th [17]<->9th [16])

i = 5:  [2, 7, 11, 16, 16, 17 , 39, 32, 38, 31 ] (5th [31]<->9th [17])

i = 6:  [2, 7, 11, 16, 16, 17, 31 , 32, 38, 39 ] (6th [39]<->9th [31])

i = 7:  [2, 7, 11, 16, 16, 17, 31, 32, 38, 39] ( 无需交换 )

i = 8:  [2, 7, 11, 16, 16, 17, 31, 32, 38, 39] ( 无需交换 )

i = 9:  [2, 7, 11, 16, 16, 17, 31, 32, 38, 39] ( 无需交换 )

选择排序随着排序的进行(i逐渐增大),比较的次数会越来越少,但是不论数组初始是否有序,选择排序都会从i至数组末尾进行一次选择比较,所以给定长度的数组,选择排序的比较次数是固定的:1+2+3+…+n=n*(n+1)/2,而交换的次数则跟初始数组的顺序有关,如果初始数组顺序为随机,则在最坏情况下数组元素将会交换N次,最好的情况是0次。选择排序的时间复杂度和空间复杂度分别为O(n2 ) O(1)

package algorithms;

 

publicabstractclass Sorter<E extends Comparable<E>>  {

    publicabstractvoid sort(E[] array,int from ,int len);

    publicfinalvoid sort(E[] array)

    {

        sort(array,0,array.length);

    }

    protectedfinalvoid swap(E[] array,int from ,int to)

    {

        E tmp=array[from];

        array[from]=array[to];

        array[to]=tmp;

    }

      publicvoid sort(String helloString, int from, int len) {

            // TODO Auto-generated method stub

           

      }

}

package algorithms;

/**

 * @author yovn

 *

 */

publicclass SelectSorter<E extends Comparable<E>> extends Sorter<E> {

 

      /* (non-Javadoc)

     * @see algorithms.Sorter#sort(E[], int, int)

     */

    @Override

    publicvoid sort(E[] array, int from, int len) {

        for(int i=0;i<len;i++)

        {

            int smallest=i;

            int j=i+from;

            for(;j<from+len;j++)

            {

                if(array[j].compareTo(array[smallest])<0)

                {

                    smallest=j;

                }

            }

            swap(array,i,smallest);

                  

        }

 

    }

   

    publicstaticvoid main(String[] args){

      String[] myStringArray = new String[3];

      String[] myStringArray1 = {"a","c","b"};

      String[] myStringArray2 = new String[]{"a","b","c"};

      SelectSorter<String> s1 = new SelectSorter<String>();

      for(int i=0;i<3;i++){

            System.out.println(myStringArray1[i]);

      }

      s1.sort(myStringArray1, 0, 3);

      for(int i=0;i<3;i++){

            System.out.println(myStringArray1[i]);

      }

    }

 

}

Output:

a

c

b

a

b

c

你可能感兴趣的:(Java排序)