`

各种排序算法及其java程序实现(2) -- 选择排序

 
阅读更多

选择排序

1. 基本思想:

  每一趟从待排序的数据元素中选出最小(或最大)的一个元素,顺序放在已排好序的数列的最后,直到全部待排序的数据元素排完。

2. 排序过程:

【示例】:

  初始关键字[49 38 65 97 76 13 27 49]

第一趟排序后13 [38 65 97 76 49 27 49]

第二趟排序后13 27 [65 97 76 49 38 49]

第三趟排序后13 27 38 [97 76 49 65 49]

第四趟排序后13 27 38 49 [49 97 65 76]

第五趟排序后13 27 38 49 49 [97 97 76]

第六趟排序后13 27 38 49 49 76 [76 97]

第七趟排序后13 27 38 49 49 76 76 [ 97]

最后排序结果13 27 38 49 49 76 76 97

 

java代码实现:

 

package test.suanfa;

public class SelectSort {

	public static void main(String[] args) {
		Integer[] intgArr = { 5, 9, 1, 4, 2, 6, 3, 8, 0, 7 };
		SelectSort insertSort = new SelectSort();
		insertSort.select(intgArr);
		for (Integer intObj : intgArr) {
			System.out.print(intObj + " ");
		}
	}

	public void select(Integer[] array) {

		int minIndex;// 最小索引

		/*
		 * 
		 * 循环整个数组(其实这里的上界为array.length - 1 即可,因为当i= array.length-1
		 * 
		 * 时,最后一个元素就已是最大的了,如果为array.length时,内层循环将不再循环),每轮假设
		 * 
		 * 第一个元素为最小元素,如果从第一元素后能选出比第一个元素更小元素,则让让最小元素与第一
		 * 
		 * 个元素交换
		 */

		for (int i = 0; i < array.length; i++) {

			minIndex = i;// 假设每轮第一个元素为最小元素

			// 从假设的最小元素的下一元素开始循环

			for (int j = i + 1; j < array.length; j++) {

				// 如果发现有比当前array[smallIndex]更小元素,则记下该元素的索引于smallIndex中

				if ((array[j].compareTo(array[minIndex])) < 0) {

					minIndex = j;

				}

			}

			// 先前只是记录最小元素索引,当最小元素索引确定后,再与每轮的第一个元素交换

			swap(array, i, minIndex);

		}

	}

	public static void swap(Integer[] intgArr, int x, int y) {

		// Integer temp; //这个也行

		int temp;

		temp = intgArr[x];

		intgArr[x] = intgArr[y];

		intgArr[y] = temp;

	}

}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics