3. 排序算法之選擇排序

排序算法之選擇排序

80000長度的數據值在[0,800000)之間的數據本機使用選擇排序,耗時10s;

1. 選擇排序

1.1 基本介紹

​ 選擇式排序也屬於內部排序法,是從欲排序的數據中,按指定的規則選出某一元素,再依規定交換位置後達到排序的目的。

1.2 選擇排序思想

​ 選擇排序(select sorting)也是一種簡單的排序方法。它的基本思想是:第一次從 arr[0]~arr[n-1]中選取最小值,與 arr[0]交換,第二次從 arr[1]~arr[n-1]中選取最小值,與 arr[1]交換,第三次從 arr[2]~arr[n-1]中選取最小值,與 arr[2]交換,…,第 i 次從 arr[i-1]~arr[n-1]中選取最小值,與 arr[i-1]交換,…, 第 n-1 次從 arr[n-2]~arr[n-1]中選取最小值,與 arr[n-2]交換,總共通過 n-1 次,得到一個按排序碼從小到大排列的有序序列。

1.3 選擇排序詳細過程

在這裏插入圖片描述

1.4 代碼實現

public class SelectSort {
	public static void main(String[] args) {
	
	}

	/**
	 * 選擇排序的方法
	 * @param arr
	 */
	public static void selectSort(int[] arr) {
		
		for (int j = 0; j < arr.length-1; j++) {
			
			int minIndex = j;
			int min = arr[j];
			
			for (int i = j + 1; i < arr.length; i++) {
				if(arr[minIndex]>arr[i]) {
					minIndex = i;
					min = arr[i];
				}
			}
			
			if(minIndex!=j) {
				arr[minIndex] = arr[j];
				arr[j] = min;
			}
			
			//System.out.println("第"+(j+1)+"輪後的arr"+Arrays.toString(arr));
			
		}
		
	}
	
}

1.5 測試結果及運行時間

public class SelectSort {

	/**
	 * 八萬個數據排序:選擇排序消耗10s
	 * @param args
	 */
	public static void main(String[] args) {
		//int[] arr = {2,1,4,3};
		int[] arr = new int[80000];
		for (int i = 0; i < arr.length; i++) {
			arr[i] = (int)(Math.random()*800000);
		}
		Date date1 = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		String format1 = simpleDateFormat.format(date1);
		System.out.println("排序前的時間:"+format1);
		selectSort(arr);
	
		
		Date date2 = new Date();
		
		String format2 = simpleDateFormat.format(date2);
		System.out.println("排序的時間:"+format2);
	}	
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章