我在做 C 时遇到了选择排序。我相当确定我理解它,但只是想确定一下。 (请不要仅仅因为还有其他问题涉及选择排序而将此问题标记为重复 - 这更多的是为了理解而不是应用)。
我的理解是(伪代码形式):
循环数字数组:将第一个数字设置为最低。循环遍历其余的,检查每个新数字到当前的最低值。如果新数字较低,则将其设置为新的最低值。循环一遍后,我们就知道最低的了。
将当前最低元素与未排序数组的第一个元素交换。现在这是“已排序”部分的一部分。循环遍历数组的未排序部分(除了第一个元素之外的所有部分)并找到新的最低元素并将其分配给“lowest”。将最低的元素与第一个未排序的元素交换。重复。
for i = 1 to n - 1
min = i
for j = i + 1 to n
if array[j] < array[min]
min = j
if min != i
swap array[min] and array[i]
如果我不在任何地方,请告诉我。
此外,如果有人可以用实际的 C 语言编写一个简单选择排序的快速示例,那就太好了!
最佳答案
是的,正确:
The selection sort is a combination of searching and sorting. During each pass, the unsorted element with the smallest (or largest) value is moved to its proper position in the array. The number of times the sort passes through the array is one less than the number of items in the array.
c 中的简单选择排序:
#include <stdio.h>
int main()
{
int array[100], n, c, d, position, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for ( c = 0 ; c < n ; c++ )
scanf("%d", &array[c]);
for ( c = 0 ; c < ( n - 1 ) ; c++ )
{
position = c;
for ( d = c + 1 ; d < n ; d++ )
{
if ( array[position] > array[d] )
position = d;
}
if ( position != c )
{
swap = array[c];
array[c] = array[position];
array[position] = swap;
}
}
printf("Sorted list in ascending order:\n");
for ( c = 0 ; c < n ; c++ )
printf("%d\n", array[c]);
return 0;
}
输出:
C02QT2UBFVH6-lm:~ gsamaras$ gcc -Wall main.c
C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
Enter number of elements
4
Enter 4 integers
1
2
6
-7
Sorted list in ascending order:
-7
1
2
6
关于关于选择排序的澄清?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39652435/