c - 选择排序功能错误

标签 c arrays function sorting data-structures

我的选择排序代码

#include <stdio.h>

void selection_sort(int a[], int n);

int main()
{
    int size;

    printf("Enter the size of array: ");
    scanf("%d",&size);

    int b[size],i = 0;
    printf("Enter %d integers to be sorted: ",size);
    while(i++ < size)
        scanf("%d",&b[i]);
    selection_sort(b, size);

    printf("Sorted integers(by selection sort) are: ");
    for(int i = 0; i < size; i++)
          printf("%d",b[i]);

    return 0;       
}

void selection_sort(int a[], int n)
{   
    while(n >= 0 )
    {
        if(n == 0)
            break;
        else
        {
            int i = 0, c = 0;
            int largest = a[0];
            while(i++ < n)
                if(largest < a[i])
                {
                    c = i ;
                    largest = a[i];
                }
            int temp = a[--n];
            a[n] = largest;
            a[c] = temp;
            selection_sort(a, n);
       } 

    }

}

按升序对数组进行排序

3    4    1    2

给出奇怪的输出

2293388    4    3    0

我检查了很多次,但未能解决问题。 我应该怎么做才能正常工作?
使用的算法:
1. 寻找数组中最大的元素。
2. 将最大的元素移动到数组的最后一个位置。
3.递归调用自身对数组的第n -1个元素进行排序。

请不要给出任何其他解决方案,否则我会感到困惑。

最佳答案

编辑

啊,我知道出了什么问题。首先,while (i++ < n)不完全按照您的期望去做。它检查条件是否 i < n为真,则递增 i .但是,似乎在条件检查之后,i体内已经递增。例如,

while (i++ < n)
   printf ("%d ", i);

将打印出来(使用 n=4 ):

1 2 3 4

所以你首先需要改变它。其次,根本不需要外部 while 循环。使用一个循环就足够了。同样,将此处的 while 循环更改为 while (i < n)并增加 i在 body 里。所以最终代码将是:

#include <stdio.h>

void selection_sort(int a[], int n);

int main()
{
    int size;

    printf("Enter the size of array: ");
    scanf("%d", &size);

    int b[size], i = 0;
    printf("Enter %d integers to be sorted: ", size);
    while(i < size) {
        scanf("%d", &b[i]);
        i++;
    }

    selection_sort(b, size);

    printf("Sorted integers(by selection sort) are: ");
    i = 0;
    for(i = 0; i < size; i++)
          printf("%d ", b[i]);

    printf ("\n");
    return 0;       
}

void selection_sort(int a[], int n)
{   
    if(n == 0)
        return;
    else
    {
        int i = 0, c = 0;
        int largest = a[0];
        while(i < n) {
            if(largest < a[i])
            {
                c = i;
                largest = a[i];
            }
            i++;
        }

        int temp = a[--n];
        a[n] = a[c];
        a[c] = temp;
        selection_sort(a, n);
    } 
}

我用你给定的输入(3 4 1 2)测试了它,它打印出一个排序列表:1 2 3 4 .

关于c - 选择排序功能错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17409831/

相关文章:

c - 在任务描述符的底部添加一个新字段

c - 有没有办法将 scanf 与 "if"和 "else"语句一起使用?

c - Getchar 只获取 char 一次

ios - 重新加载 Swift Array 的内容而不重新分配它?

php - 数组中的两个 PHP 值

javascript - JS : Remove object from nested array and return parent array

python - 如何覆盖 if 语句中的函数?

sql - 带有 PostGis 的 Postgres 中的触摸功能

c - 在监控模式下注册 pcap 处理程序

matlab - 寻找矩阵中的临界点