【C语言】用选择法、冒泡法分别对10个整数从小到大排序

【C语言】用选择法对10个整数从小到大排序:

#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

void SelectSort(int array[], int length){
    int i, j, min, temp;
    for(i=0; i<length-1; i++){                                //一共进行length-1趟
        min = i;                                                     //记录最小元素位置
        for(j=i+1; j<length; j++){                            //在array[i-----n-1]中选择最小的元素
            if(array[j]<array[min]) min = j;               //更新最小元素位置
        }
        if(min!=i){                                                  //与第i个位置交换
            temp = array[i];
            array[i] = array[min];
            array[min] = temp;
        }
    }
}

int main(int argc, char *argv[]) {
    int array_length = 10;
    int a[array_length];
    int i;
    printf("请输入10个整数:");
    for(i=0; i<array_length; i++){
        scanf("%d", &a[i]);
    }
    SelectSort(a, array_length);
    printf("排序后的元素为:\n");
    for(i=0; i<array_length; i++){
        printf("%d ", a[i]);
    }
    printf("\n");
    return 0;
}

 

 

【C语言】用冒泡法对10个整数从小到大排序:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {
    int i, j, a[10], temp;
    printf("请输入10个整数:");
    for(i=0; i<10; i++){
        scanf("%d", &a[i]);
    }
    for(i=0; i<9; i++){
        for(j=0; j<9; j++){
            if(a[j]>a[j+1]){
                temp = a[j];
                a[j] = a[j+1];
                a[j+1] = temp;
            }
        }
    }
    printf("排序后的数字为:"); 
    for(i=0; i<10; i++){
        printf("%d ", a[i]);
    }
    return 0;
}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值