Proyecto
This function sorts an array using the algorithm known as selection sort. The array is composed of elements of type int, holding a single integer. Because C has no way to determinethe number of elements in an array, this is passed as a second argument to the function.
Selection sort uses two nested loops. The first time through the outer loop, the inner loop finds the element inthe array that has the lowest number. It then swaps that element with the element in the first position in the array, so that the first element now has the lowest number in it. The outer loop theniterates again, finding the next lowest number in the array and swapping that into the second position, and so on.
Source Code
1. void sort (
2. int a[],
3. int n) {4.
5. int current, j, lowestindex, temp;
6.
7. for (current = 0; current < n-1; current++) {
8.
9. //
10. // each time throughthis loop, scan the array
11. // from current+1 to the end. If we find
12. // something lower than what is at current, then
13. // swap it with currentindex. So each time
14. // through this loop, a[current] will be
15. // properly sorted.
16. //
17. // 1) first find the index of thelowest value
18. //
19. // If lowestindex remains unchanged, a[current]
20. // is already sorted.
21. //
22.
23.lowestindex = current;
24.
25. for (j = current+1; j < n; j++) {
26. if (a[j] < a[current]) {
27. lowestindex = j;
28. }29. }
30.
31. //
32. // 2) now swap a[current] and a[lowestindex],
33. // as long as a difference was found.
34. //...
Regístrate para leer el documento completo.