递归冒泡题22222

Q3091.(50分)采用冒泡法进行升序排序。
基本原理是:对数组中的n个数执行n-1遍检查操作,在每一遍执行时,对数组中剩余的尚未排好序的元素进行如下操作:对相邻的两个元素进行比较,若排在后面的数小于排在前面的数,则交换其位置,这样每一遍操作中都将参与比较的数中的最大的数沉到数组的底部,经过n-1遍操作后将全部n个数按从小到大的顺序排好序。
要求限制数组元素最大个数为10。
程序的某次运行结果如下:
Input n:5∠
Input 5 numbers:21 32 45 12 0/
Sorting results: 0 12 2132 45(换行)
输入格式:“%d”
输入数据个数提示:“Input n:”
输入数据提示:"Input %d numbers:"
输出提示:"Sorting results:”
输出数据格式:“%4d”

参考如下:


#include<stdio.h>


void sort(int a[],int n)
{
    int i,j,t,noswap;
    for(i=0;i< n-1; i++)
    {
        noswap=1;
        for(j=n-1;j>i;j--)
            if(a[j-1]>a[j])
            {
                t=a[j-1];
                a[j-1]=a[j];
                a[j]=t;
                noswap=0;
            }
        if(noswap)    
            break;
    }
}

int main() 
{
     
    int n;
    printf("Input n:");
    scanf("%d", &n);
     
    printf("Input %d numbers:", n);

    int a[n];
    for (int i = 0; i < n; i++) {
        scanf("%d", &a[i]);
    }

    sort(a, n);

    printf("Sorting results:");
    for (int i = 0; i < n; i++) {
        printf("%4d", a[i]);
    }

    return 0;
}

img


如有帮助,欢迎采纳哈!

在这里插入图片描述

本人的开源项目,欢迎star支持下!!!