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
| #include <stdio.h>
#define ARRSIZE(arr) (sizeof(arr) / sizeof(arr[0]))
void Swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
void SelectionSort(int elements[], int length)
{
for (int i = 0; i < length; i++)
{
int min = i; //默认最小的下标为i
for (int j = i; j < length; j++)
{
if (elements[j] < elements[min])
min = j;//找到更小的则更新min
}
//已找到第i个最小元素,进行交换
Swap(&elements[min], &elements[i]);
}
}
int main(int argc, char const *argv[])
{
int elems[] = {3, 4, 2, 1, 5, 9, 2, 1, 0, 22, 33, 5, 112, 11, 22, 55, 22, 61, 97};
int len = ARRSIZE(elems);
SelectionSort(elems, len);
for (int i = 0; i < len; i++)
printf("%4d", elems[i]);
printf("\n");
return 0;
}
|