我正在尝试打印排序函数的迭代,它似乎有效但有一些额外的数字

问题描述

void SelectionSort(int arr[],int n)
{
    int i,j,min_idx;
    // One by one move boundary of unsorted subarray
    for (i = 0; i < n-1; i++)
    {
        // Find the minimum element in unsorted array
        min_idx = i;
        PrintArray(&arr[i],n);
        for (j = i+1; j < n; j++)
            if (arr[j] < arr[min_idx])
                min_idx = j;
            // Swap the found minimum element with the first element
                Swap(&arr[min_idx],&arr[i]);
    }
}
void PrintArray(int arr[],int n)
{
    int i;
    for (i = 0; i < n; i++)
        printf("%d ",arr[i]);
    printf("\n");
}

this is the output I'm getting

我正在尝试打印排序过程的每次迭代,我已经分别测试了排序功能和打印功能,它们都可以工作,我尝试将打印功能放在循环中的不同位置,但没有工作。我是 c 和编程的新手,所以如果你也能向我解释这些步骤,我将不胜感激。 谢谢

解决方法

请注意,您正在将数组从第 i 个元素开始传递给您的打印函数,但是您的打印函数通过将 n 初始化为期望数组具有 i 元素0 循环中的 for。因此,您实际上是在数组外打印元素。这也解释了为什么您总是打印 n 元素,并且附加数字的数量每次都会增加。

我建议您在程序中使用 valgrind。它显示了您的程序中可能发生的各种内存错误。这是访问分配给您的内存之外的内存的示例,它会捕获。它还告诉您在运行结束时内存泄漏(即您没有释放的内存)。

此外,即使块的长度为 1 个命令,也不要在代码中省略大括号。它使您的代码可读性大大降低,并可能因此导致错误。

void PrintArray(int arr[],int n) { 
    int i; 
    for (i = 0; i < n; i++) {
        printf("%d ",arr[i]); 
    }
    printf("\n"); 
} 
,

这个电话

PrintArray(&arr[i],n);

始终使用变量 n 中存储的值作为数组的输出元素数。因此,与起始索引 i 无关,该函数将尝试准确输出 n 元素,从而导致访问数组之外​​的内存。

你必须写

PrintArray( &arr[i],n - i );

PrintArray( arr + i,n - i );

但是,您似乎想在每次迭代中输出整个数组。如果是这样,那么你应该只写

PrintArray( arr,n );

还要注意的是,指定数组元素个数的参数应该使用类型size_t而不是类型int,因为int类型的对象通常不能大到足以存储数组中可能的元素数量。

那就是你的函数应该声明为

void SelectionSort(int arr[],size_t n);

相应地,函数 PrintArray 应该声明为

void PrintArray( const int arr[],size_t n );

注意第一个参数有限定符const,因为数组的元素在函数内没有改变。

此外,您应该交换数组中的两个元素,以防它们不是同一个元素。

这是一个演示程序。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void PrintArray( const int [],size_t );
void Swap( int *,int * );

void SelectionSort( int arr[],size_t n )
{
    for ( size_t i = 1; i < n; i++ )
    {
        PrintArray( arr + i - 1,n - i - 1 );
        
        size_t min_idx = i - 1;

        for ( size_t j = i; j < n; j++ )
        {
            if ( arr[j] < arr[min_idx] ) min_idx = j;
        }           

        if ( min_idx != i - 1 ) Swap( &arr[min_idx],&arr[i-1] );
    }
}

void PrintArray( const int arr[],size_t n )
{
    for ( size_t i = 0; i < n; i++ )
    {
        printf( "%d ",arr[i] );
    }       
    putchar( '\n' );
}

void Swap( int *a,int *b )
{
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

int main(void) 
{
    enum { N = 10 };
    int a[N];
    
    srand( ( unsigned int )time( NULL ) );
    
    for ( size_t i = 0; i < N; i++ )
    {
        a[i] = rand() % N;
    }
    
    SelectionSort( a,N );
    
    PrintArray( a,N );
    
    return 0;
}

程序输出为

2 2 9 2 3 9 3 2 
2 9 2 3 9 3 2 
9 2 3 9 3 2 
9 3 9 3 2 
3 9 3 9 
9 3 9 
9 9 
9 

2 2 2 2 2 3 3 5 9 9