C 语言插入排序程序

用 C 语言使用 For 循环、While 循环和函数编写一个使用插入排序的数组排序程序,并附带实际示例。

C 语言插入排序程序(使用 For 循环)

此插入排序程序允许用户输入数组大小和一维数组的元素。接下来,我们使用嵌套的 For 循环通过插入排序来对数组元素进行排序。

#include <stdio.h>
int main()
{
    int a[100], number, i, j, temp;
    
    printf("\n Please Enter the total Number of Elements  :  ");
    scanf("%d", &number);
    
    printf("\n Please Enter the Array Elements  :  ");
    for(i = 0; i < number; i++)
        scanf("%d", &a[i]);
    
    for(i = 1; i <= number - 1; i++)
    {
        for(j = i; j > 0 && a[j - 1] > a[j]; j--)
        {
                temp = a[j];
                a[j] = a[j - 1];
                a[j - 1] = temp;
        }
    }
    printf("\n Insertion Sort Result : ");
    for(i = 0; i < number; i++)
    {
        printf(" %d \t", a[i]);
    }
    printf("\n");
    return 0;
}
Program for Insertion Sort

第一个 For 循环 – 第一次迭代: for(i = 1; 1 <= 4; 1++)

条件为真,因此 C 语言程序将进入第二个 for 循环。

第二个 For 循环 – 第一次迭代: for(j = 1; 1 > 0 && a[0] > a[1]; 1–)
(a[0] > a[1]) => (10 > -20) – For 循环内的条件为真
temp = -20
a[j] = a[j – 1] => a[1] = a[0] => a[1] = 10
a[j – 1] = temp => a[0] = -20
现在数组将是 -20 10 10 3 15。

对一维数组剩余的 For 循环迭代执行相同操作。

C 语言插入排序程序(使用 While 循环)

在此程序中,我们用 While 循环替换了 for 循环,以使用插入排序算法对数组元素进行排序。

// using a while loop
#include <stdio.h>
int main()
{
    int a[100], number, i, j, temp;
    
    printf("\n Please Enter the total Number of Elements  :  ");
    scanf("%d", &number);
    
    printf("\n Please Enter the Array Elements  :  ");
    for(i = 0; i < number; i++)
        scanf("%d", &a[i]);
    
    i = 1;
    while( i <= number - 1)
    {
        j = i;
        while( j > 0 && a[j - 1] > a[j])
        {
            temp = a[j];
            a[j] = a[j - 1];
            a[j - 1] = temp;
            j--;
        }
        i++;
    }
    printf("\n Result : ");
    for(i = 0; i < number; i++)
    {
        printf(" %d \t", a[i]);
    }
    printf("\n");
    return 0;
}
Please Enter the total Number of Elements  :  6

 Please Enter the Array Elements  :  2 12 -9 7 0 -22

 Result :  -22 	 -9 	 0 	 2 	 7 	 12 	

使用函数的插入排序程序

此插入程序使用函数对数组元素进行排序。

#include <stdio.h>
void insFunc(int a[], int num) {
    int i, j, temp;
    for(i = 1; i <= num - 1; i++)
    {
        for(j = i; j > 0 && a[j - 1] > a[j]; j--)
        {
            temp = a[j];
            a[j] = a[j - 1];
            a[j - 1] = temp;
        }
    }
}
int main()
{
    int a[100], num, i;
    
    printf("\n Please Enter the total No. of Elements  :  ");
    scanf("%d", &num);
    
    printf("\n Please Enter the Array Elements  :  ");
    for(i = 0; i < num; i++)
        scanf("%d", &a[i]);

    insFunc(a, num);
    printf("\n Output : ");
    for(i = 0; i < num; i++)  {
        printf(" %d \t", a[i]);
    }
    printf("\n");
    return 0;
}
Please Enter the total No. of Elements  :  5

 Please Enter the Array Elements  :  10 5 -3 2 -22

 Output :  -22 	 -3 	 2 	 5 	 10