JAVA 选择排序 推理过程

版权声明: https://blog.csdn.net/m0_37682436/article/details/83502085

选择法排序的思路: 
把第一位和其他所有的进行比较,只要比第一位小的,就换到第一个位置来 
比较完后,第一位就是最小的 
然后再从第二位和剩余的其他所有进行比较,只要比第二位小,就换到第二个位置来 
比较完后,第二位就是第二小的 
以此类推

​​​​​​​

// 初始化数组
		int[] a = { 5, 7, 4, 3, 8, 9 };
		// 查看数组
		for (int i : a) {
			System.out.print(i + " ");
		}
		System.out.println();

		// 第一次 寻找到最小的
		for (int i = 0; i < a.length; i++) {
			if (a[i] < a[0]) {
				int temp = a[i];
				a[i] = a[0];
				a[0] = temp;
			}
		}
		for (int i : a) {
			System.out.print(i + " ");
		}
		System.out.println();

		// 第二次 比较第二位
		for (int i = 1; i < a.length; i++) {
			if (a[i] < a[1]) {
				int temp = a[i];
				a[i] = a[1];
				a[1] = temp;
			}
		}

		for (int i : a) {
			System.out.print(i + " ");
		}
		System.out.println();

		// 总结 依次循环 查找最小
		for (int j = 0; j < a.length; j++) {
			for (int i = j + 1; i < a.length; i++) {
				if (a[i] < a[j]) {
					int temp = a[i];
					a[i] = a[j];
					a[j] = temp;
				}
			}
		}
		for (int i : a) {
			System.out.print(i + " ");
		}
		System.out.println();

最终代码格式  依照习惯写

for (int i = 0; i < a.length; i++) {
	for (int j = i + 1; j < a.length; j++) {
		if (a[j] < a[i]) {
			int temp = a[j];
			a[j] = a[i];
			a[i] = temp;
		}
	}
}

猜你喜欢

转载自blog.csdn.net/m0_37682436/article/details/83502085
今日推荐