C Exercise 37 - Sorting
100 Classic C Language Examples
**Problem:** Sort 10 numbers.
**Program Analysis:** You can use the selection method: from the 9 comparisons, select the smallest and swap it with the first element; repeat similarly, using the second element compared with the remaining 8 and swapping.
Example
#include
<
stdio.h
#define
N
10
void
selectionSort
(
int
arr
[
]
,
int
n
)
{
int
i
,
j
,
minIndex
,
temp;
for
(
i
=
0
;
i
<
n
1;
i
++
)
{
minIndex
=
i
;
for
(
j
=
i
1
;
j
<
n
;
j
++
)
{
if
(
arr
[
j
]
<
arr
[
minIndex
]
)
{
minIndex
=
j;
}
}
if
(
minIndex
!=
i
)
{
// Swap the elements
temp
=
arr
[
i
]
;
arr
[
i
]
=
arr
[
minIndex
]
;
arr
[
minIndex
]
=
temp
;
}
}
}
int
main
(
)
{
int
arr
[
N
]
;
printf
(
"
Please enter %d numbers:
\
n
"
,
N
)
;
for
(
int
i
=
0
;
i
<
N
;
i
++
)
{
scanf
(
"
%d
"
, &
arr
[
i
]
)
;
}
selectionSort
(
arr
,
N
)
;
printf
(
"
The sorted result is:
\
n
"
)
;
for
(
int
i
=
0
;
i
<
N
;
i
++
)
{
printf
(
"
%d
"
,
arr
[
i
]
)
;
}
printf
(
"
\
n
"
)
;
return
0
;
}
The output of the above example is:
Please enter 10 numbers:
23 2 27 98 234 1 4 90 88 34
The sorted result is:
1 2 4 23 27 34 88 90 98 234