0%

选择排序

选择排序含义及代码示例

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sort
{
class SelectSorter
{
public static int[] Sort(int[] a)
{
SelectSort(a);
return a;
}

private static void SelectSort(int[] myArray)
{
int i, j, smallest;
//数据起始位置,从0到倒数第二个数据
for (i = 0; i < myArray.Length - 1; i++)
{
smallest = i;//记录最小数据的下标
for (j = i + 1; j < myArray.Length; j++)
{
//在剩下的数据中寻找最小数据
if (myArray[j] < myArray[smallest])
{
smallest = j;//如果有比它更小的,记录下标
}
}
//将最小数据和未排序的第一个数据交换
Swap(ref myArray[i], ref myArray[smallest]);
}
}

private static void Swap(ref int left, ref int right)
{
int temp;
temp = left;
left = right;
right = temp;
}

}
}

思想

例子