排序-----选择排序

选择排序(SelectionSort)

定义:每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,直到全部待排序的数据元素排完。就数组a来说,选择排序找到数组中的最小的项,将他与a[0]交换,然后忽略a[0],排序找到下一个最小的项并换到a[1],以此类推。

如图:

                                    

Java代码:

<1>迭代选择排序

public class SelectionSort{
	public static <T extends Comparable<? super T>> void SelectionSort(T[] a,int n) {
		for(int index = 0;index<n-1;index++) {    
                    //  得到下一个最小数

			int indexOfNextSmallest = getIndexOfSmallest(a,index,n-1);
			swap(a, indexOfNextSmallest, index);
		}
	} 

    private static <T extends Comparable<? super T>> int getIndexOfSmallest(T[]a,int first,int last){
		T min = a[first];
		int indexOfMin = first;
		for(int index = first+1;index<=last;index++) {
			if(a[index].compareTo(min)<0) {
				min = a[index];
				indexOfMin = index;
			}
		}
		return indexOfMin;
	}
	private static void swap(Object[] a,int i, int j) {
		Object temp = a[i];
		a[i]=a[j];
		a[j]=temp;
	}
}

测试代码: 

public class testSort {

	public static  void main(String[] args) {
		Integer[] a = {9,8,7,6,5,4,3,2,1};
		SelectionSort.SelectionSort(a, 9);
		for(Integer integer:a) {
			System.out.println(integer);
		}	
	}
}

<2> 递归选择排序

public class RecursionSort {
	public static <T extends Comparable<? super T>> void SelectionSort (T[] a,int first,int last) {
		if(first<last) {
			int indexOfNextSmallest = getIndexOfSmallest(a, first, last);
			swap(a, first, indexOfNextSmallest);
			SelectionSort(a,first+1,last);
		}
		
	}
	private static <T extends Comparable<? super T>> int getIndexOfSmallest(T[]a,int first,int last){
		T min = a[first];
		int indexOfMin = first;
		for(int index = first+1;index<=last;index++) {
			if(a[index].compareTo(min)<0) {
				min = a[index];
				indexOfMin = index;
			}
		}
		return indexOfMin;
	}
	private static void swap(Object[] a,int i, int j) {
		Object temp = a[i];
		a[i]=a[j];
		a[j]=temp;
	}
	public static void main(String[] args) {
		Integer[] a = {23,42,43,2,42,43,23,42,4,23,42,34,2,42,34,2};
		Recursion.SelectionSort(a,0,a.length-1);
		for(Integer integer:a) {
			System.out.println(integer);
		}
		
	}
	
}

选择排序时间效率:

        在迭代方法selectionSort中,for循环每执行n-1次,分别调用getIndexOfSmallest和swap方法各n-1次。在n-1次调用getIndexOfSmallest中,last是n-1,first从0变到n-2。在每次调用getIndexOfSmallest时,循环执行last-first次。因为last-first从(n-1)-0即n-1 变到(n-1)-(n-2)即1,共执行了(n-1)+(n-2)+...+1次,这个和为n(n-1)/2。所以选择排序是O(n2)的。

冒泡排序和选择排序的区别:

冒泡排序通过依次交换相邻两个顺序不合法的元素位置,从而将当前最小(大)元素放到合适的位置;而选择排序每遍历一次都记住了当前最小(大)元素的位置,最后仅需一次交换操作即可将其放到合适的位置

猜你喜欢

转载自blog.csdn.net/qq_41304534/article/details/80719642