选择排序 selection Sort

概述

按指定的规则选出来某个元素,再依规定交换位置.可以不断缩小范围将最小值放在前方。

图解过程

// Find the minimum element in arr[0…4]
// and place it at beginning
11 25 12 22 64

// Find the minimum element in arr[1…4]
// and place it at beginning of arr[1…4]
11 12 25 22 64

// Find the minimum element in arr[2…4]
// and place it at beginning of arr[2…4]
11 12 22 25 64

// Find the minimum element in arr[3…4]
// and place it at beginning of arr[3…4]
11 12 22 25 64

造轮子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public void sort(int arr[]) 
{
int n = arr.length;

// One by one move boundary of unsorted subarray
for (int i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;

// Swap the found minimum element with the first
// element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
作者

黄港欢

发布于

2020-03-12

更新于

2021-03-10

许可协议