Java数组排序-选择排序

Java数组排序的选择排序,是将最小索引的元素依次和后面元素进行比较,小的元素放到前面,第一次比较完毕后最小的元素就会在最左边最小索引出,后面同理即可得到一个排列好的数组

选择排序也是有规则的:

1 第一次是从0索引与后面的元素进行比较的,

   第二次是从1索引和后面的元素比较的。。。

2 最后一次比较是数组的长度-2的索引元素和数组长度-1的索引元素比较

同样画图帮助理解一下

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

代码运行一下看结果

public class SelectDemo {
	public static void main(String[] args) {
		int[] arr = new int[] { 2, 34, 56, 43, 45 };

		int[] arr2 = getSelect(arr);
		for (int a : arr2) {
			System.out.print(a + " ");
		}
	}

	public static int[] getSelect(int[] arr2) {
		for (int i = 0; i < arr2.length - 1; i++) {
			int minIndex = i;
			for (int j = i + 1; j < arr2.length; j++) {
				if (arr2[minIndex] > arr2[j]) {
					minIndex = j;
				}
			}
			if (arr2[minIndex] != arr2[i]) {
				int temp = arr2[minIndex];
				arr2[minIndex] = arr2[i];
				arr2[i] = temp;
			}
		}
		return arr2;

	}

}





猜你喜欢

转载自blog.csdn.net/oman001/article/details/76263034