From cee2e5d0dbcf5acabff564f187c107db599d611e Mon Sep 17 00:00:00 2001 From: WalterWen <1498592764@qq.com> Date: Thu, 6 Jun 2019 21:41:47 +0800 Subject: [PATCH] =?UTF-8?q?=E9=80=89=E6=8B=A9=E6=8E=92=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/com/we/sort/SelectionSort.java | 49 ++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/com/we/sort/SelectionSort.java diff --git a/src/com/we/sort/SelectionSort.java b/src/com/we/sort/SelectionSort.java new file mode 100644 index 0000000..507f931 --- /dev/null +++ b/src/com/we/sort/SelectionSort.java @@ -0,0 +1,49 @@ +package com.we.sort; + +public class SelectionSort { + public void selectionSort(int[] list) { + + // 总共要经过 N-1 轮比较 + for (int i = 0; i < list.length - 1; i++) { + int min = i; + + // 每轮需要比较的次数 N-i + for (int j = i + 1; j < list.length; j++) { + if (list[j] < list[min]) { + // 记录目前能找到的最小值元素的下标 + min = j; + } + } + // 将找到的最小值和i位置所在的值进行交换 + if (i != min) { + int tmp = list[i]; + list[i] = list[min]; + list[min] = tmp; + } + + System.out.format("第 %d 趟: ", i); + printAll(list); + } + + } + + // 打印完整序列 + public void printAll(int[] list) { + for (int value : list) { + System.out.print(value + " "); + } + System.out.println(); + } + + public static void main(String[] args) { + + int array[] = {3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48}; + // 调用冒泡排序方法 + SelectionSort bubble = new SelectionSort(); + System.out.print("排序前: "); + bubble.printAll(array); + bubble.selectionSort(array); + System.out.print("排序后: "); + bubble.printAll(array); + } +} -- GitLab