首页 > 编程语言 > 详细

选择排序法(Selection Sort) 复习--附图示说明

时间:2015-06-22 06:27:54      阅读:156      评论:0      收藏:0      [点我收藏+]

先看看图示了解 Selection Sort 是怎麽完成的

技术分享


技术分享

技术分享

技术分享

技术分享


技术分享

技术分享

技术分享


技术分享

技术分享

技术分享

技术分享

最後完成了~ 了解了它的行为模式以後,我们可以开始写代码实现了

import java.util.Arrays;

public class testMain {
	public static void main(String[] args) {
		int[] randArray = new int[] { 2, 0, 1, 3, 9, 8, 6, 5, 4, 7 };
		insertionSort(randArray);
		System.out.println(Arrays.toString(randArray));
	}

	public static void insertionSort(int[] intArray) {
		int size = intArray.length;
		for (int cur = 1; cur < size; cur++) {
			int j = cur;
			while (j > 0 && intArray[j] < intArray[j - 1]) {
				int temp = intArray[j - 1]; // 做交换
				intArray[j - 1] = intArray[j];
				intArray[j] = temp; 
				j--; // 交换完後,往前移,持续往前比较
			}

		}
	}
}
中间发现了一个问题,就是在判断式中如果 j> 0 放後面的时候,即使有 && 符号, j = 0 一样会进入判断式,即是

intArray[j - 1] 中,便会造成数组越界 (intArray[-1]) 的异常,所以我们得将 j > 0 放前面。

			while (intArray[j] < intArray[j - 1] && j > 0) {
				int temp = intArray[j - 1]; // 做交换
				intArray[j - 1] = intArray[j];
				intArray[j] = temp; 
				j--; // 交换完後,往前移,持续往前比较
			}
技术分享



选择排序法(Selection Sort) 复习--附图示说明

原文:http://blog.csdn.net/shanwu1985/article/details/46585999

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!