算法之选择排序

算法之选择排序代码参考

 

/**
 * 选择排序
 * 
 * @author zhang
 *
 */
public class SelectSort {

	public static void main(String[] args) {
		int[] arr = new int[] { 1, 9, 2, 0, 5, 6, 5, 9, 5, 7, 3, 7 };
		SelectSortMethod(arr);
		System.out.println(Arrays.toString(arr));
	}

	public static void SelectSortMethod(int[] arr) {

		// 遍历所有的数
		for (int i = 0; i < arr.length; i++) {

			// 假设当前i是最小的
			int minIndex = i;

			// 将当前所有的数和后面的数 依次比较,找到最小的数,并记录下标
			for (int j = i + 1; j < arr.length; j++) {
				// 如果后面的数,比假设记录的最小值小
				if (arr[j] < arr[minIndex]) {
					// 记录最小的下标
					minIndex = j;
				}

			}
			// 如果最小的数和当前遍历的数下标不一致,说明下标为min的数比当前遍历的数更小
			if (i != minIndex) {
				int temp = arr[i];
				arr[i] = arr[minIndex];
				arr[minIndex] = temp;
			}
		}

	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值