简体   繁体   English

C 中的插入排序算法不起作用

[英]Insertion sort algorithm in C is not working

I am trying to sort an array of integers for finding the median of the same array.我正在尝试对整数数组进行排序以查找同一数组的中位数。 The code I am using sorts only the first two elements of the 10 element array.我使用的代码仅对 10 元素数组的前两个元素进行排序。 I have cross checked the swapping of variables in the loops, but everything seems okay.我已经交叉检查了循环中变量的交换,但一切似乎都很好。

void sort(int *arr) {
    //get the size of this array
    int size = sizeof(arr) / sizeof(arr[0]);
    for (int i = 0; i < size; i++) {
        for (int j = i + 1; j < size; j++) {
            if (arr[i] > arr[j]) {
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
}

Application应用

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

int main() {
    int numbers[10];
    numbers[0] = 10;
    numbers[1] = 9;
    numbers[2] = 8;
    numbers[3] = 7;
    numbers[4] = 6;
    numbers[5] = 5;
    numbers[6] = 4;
    numbers[7] = 3;
    numbers[8] = 2;
    numbers[9] = 1;

    sort(numbers);
    //code sorts the element in the first and second index, the rest are unsorted please help

    return 0;
}

What am I doing wrong?我究竟做错了什么?

The function parameter has a pointer type function 参数是指针类型

void sort(int* arr){

Even if you will rewrite the function declaration like即使你会像这样重写 function 声明

void sort( int arr[10] ){

nevertheless the compiler will adjust the function parameter having the array type to pointer to the element type as it is written in your original function declaration尽管如此,编译器会将具有数组类型的 function 参数调整为指向元素类型的指针,因为它写在您的原始 function 声明中

void sort(int* arr){

And in this call of the function在 function 的这个电话中

sort(numbers);

the array designator is implicitly converted to a pointer to its first element.数组指示符隐式转换为指向其第一个元素的指针。 That is the call above in fact is the same as也就是上面的调用其实是一样的

sort( &numbers[0] );

So using the operator sizeof with a pointer expression yields the size of a pointer.因此,将运算符sizeof与指针表达式一起使用会产生指针的大小。 That is this line也就是这条线

//get the size of this array
int size=sizeof(arr)/sizeof(arr[0]);

is equivalent to相当于

//get the size of this array
int size=sizeof( int * )/sizeof( int );

and yields either 2 or 1 depending on the used system.并根据使用的系统产生 2 或 1。

You need to declare the function like您需要像这样声明 function

void sort( int *arr, size_t n );

and pass to the function the number of elements in the array explicitly.并将数组中元素的数量显式传递给 function。

Bear in mind that in general the user can use the function for a dynamically allocated array.请记住,通常用户可以将 function 用于动态分配的数组。

Pay attention to that the used by you algorithm is not the insertion sort algorithm.注意你使用的算法不是插入排序算法。 It is the selection sort algorithm with redundant swaps.它是具有冗余交换的选择排序算法。

A function that implements the insertion sort algorithm can look for example the following way as it is shown in the demonstration program below.实现插入排序算法的 function 可以如下面的演示程序所示。

#include <stdio.h>

void insertion_sort( int a[], size_t n )
{
    for ( size_t i = 1; i < n; i++ )
    {
        int current = a[i];
        size_t j = i;
        for ( ; j != 0 && current < a[j - 1]; j-- )
        {
            a[j] = a[j - 1];
        }

        if ( j != i ) a[j] = current;
    }
}

int main()
{
    int a[] = { 9,8, 7, 6, 5, 4, 3, 2, 1, 0 };
    const size_t N = sizeof( a ) / sizeof( *a );

    for (size_t i = 0; i < N; i++)
    {
        printf( "%d ", a[i] );
    }
    putchar( '\n' );

    insertion_sort( a, N );

    for (size_t i = 0; i < N; i++)
    {
        printf( "%d ", a[i] );
    }
    putchar( '\n' );
}

The program output is程序 output 是

9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9

As for the function that implements the selection sort algorithm then without redundant swaps it can look the following way as it is shown in the next demonstration program.至于 function,它实现了选择排序算法,然后没有冗余交换,它可以看起来像下一个演示程序中所示的以下方式。

#include <stdio.h>

void selection_sort( int a[], size_t n )
{
    for ( size_t i = 0; i < n; i++ )
    {
        size_t min = i;

        for ( size_t j = i + 1; j < n; j++ )
        {
            if (a[j] < a[min]) min = j;
        }

        if ( min != i )
        {
            int tmp = a[i];
            a[i] = a[min];
            a[min] = tmp;
        }
    }
}

int main()
{
    int a[] = { 9,8, 7, 6, 5, 4, 3, 2, 1, 0 };
    const size_t N = sizeof( a ) / sizeof( *a );

    for (size_t i = 0; i < N; i++)
    {
        printf( "%d ", a[i] );
    }
    putchar( '\n' );

    selection_sort( a, N );

    for (size_t i = 0; i < N; i++)
    {
        printf( "%d ", a[i] );
    }
    putchar( '\n' );
}

The program output is the same as shown above程序output同上图

9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9

This is because int size = sizeof(arr) / sizeof(arr[0]);这是因为int size = sizeof(arr) / sizeof(arr[0]); will return 2 , because sizeof(arr) will give the sizeof a pointer to int , which in your case is 8 bytes and then sizeof(arr[0]) will give a sizeof int which in your case is 4 bytes .将返回2 ,因为sizeof(arr)会给sizeof一个指向 int的指针,在你的情况下它是8 bytes然后sizeof(arr[0])会给出一个sizeof int在你的情况下是4 bytes

So,所以,

8 / 4 = 2

Fix:使固定:

  • Add another parameter for the length of the array.为数组的长度添加另一个参数。
  • type-cast numbers to (int *) for sort() functionnumbers类型转换为(int *) for sort() function
  • Your sort() function does not implement insertion sort algorithm, instead it is selection sort algorithm.您的sort() function 没有实现插入排序算法,而是选择排序算法。 READ MORE 阅读更多
  • There's no need of stdlib.h header file in your code您的代码中不需要stdlib.h header 文件

Like this: TRY IT ONLINE像这样: TRY IT ONLINE

#include <stdio.h>

void sort(int *arr, size_t len)
{
    for (int i = 0; i < len; i++)
    {
        for (int j = i + 1; j < len; j++)
        {
            if (arr[i] > arr[j])
            {
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
}

// using `const` keyword, because `arr` isn't modifying inside `print()` function
void print(const int *arr, size_t len){
    for (size_t i = 0; i < len; i++)
    {
        printf("%d\n", arr[i]);
    }
}

int main(void)
{
    int numbers[10];
    numbers[0] = 10;
    numbers[1] = 9;
    numbers[2] = 8;
    numbers[3] = 7;
    numbers[4] = 6;
    numbers[5] = 5;
    numbers[6] = 4;
    numbers[7] = 3;
    numbers[8] = 2;
    numbers[9] = 1;

    size_t len = sizeof(numbers) / sizeof(numbers[0]);
    sort((int *)numbers, len);

    print(numbers, len);
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM