当前位置:网站首页>[pointer] use the insertion sorting method to arrange n numbers from small to large

[pointer] use the insertion sorting method to arrange n numbers from small to large

2022-07-06 14:35:00 |Light|

requirement

Programming , Use insert sort to put n Sort the numbers from small to large .( Use a pointer to achieve )

Code

#include<stdio.h>
/* *  This function is used to input a one-dimensional integer array , The input data is stored in the formal parameter pointer a(a Is the first address of a one-dimensional array ) in  *  Input data in 0 As an end sign ,0 It is not stored in the array nor included in the total number of input data  *  The return value is the number of input data  */
int input(int *a)
{
    
    int n=0;
     int b = 0;
    do
    {
    
        scanf("%d",&b);
        if(b == 0)
        break;
        else
        {
    
            a[n] = b;
            n++;
        }
    }
    while(b != 0);
    return n;

}

/* *  This function implements the array (a Is the first address of a one-dimensional array , It is the array to be sorted ) Sort , After sorting, it is still stored in a in  * n Is an array a The number of numbers to be sorted in  */
void insert_sort(int *a,int n)
{
    
    int i,j,key;
        for (i=1;i<n;i++)
        {
    
                key = a[i];
                j=i-1;
                while((j>=0) && (a[j]>key)) 
                {
    
                        a[j+1] = a[j];
                        j--;
                }
                a[j+1] = key;
        }   
}

main function

 int main()
 {
    
    int a[200],n;
    n=input(a);
    insert_sort(a,n);
    for(int i=0;i<n;i++)
        printf("%d ",a[i]);
    return 0;
 }   

test

Test input
1 2 7 6 8 5 4 2 0
Output
1 2 2 4 5 6 7 8

原网站

版权声明
本文为[|Light|]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060918542372.html