C语言第十一周课——函数的调用

目录

一、冒泡法排序

二、二分法查找


一、冒泡法排序

通过调用函数来实现冒泡法

cpp 复制代码
#include<stdio.h>
// 定义数组长度
#define SIZE 3
void bubbleSort(int arr[], int n);

int main()
{
    int arr[SIZE];
    int i;

    // 从控制台输入数字到数组
    printf("请输入%d个整数:\n", SIZE);
    for (i = 0; i < SIZE; i++)
    {
        scanf("%d", &arr[i]);
    }

    // 调用冒泡排序函数
    bubbleSort(arr, SIZE);

    // 输出排序后的数组
    printf("排序后的数组为:\n");
    for (i = 0; i < SIZE; i++)
    {
        printf("%d ", arr[i]);
    }
	printf("\n");
    return 0;
}

void bubbleSort(int arr[], int n)
{
    int i, j, temp;
    for (i = 0; i < n - 1; i++)
    {
        for (j = 0; j < n - i - 1; j++)
        {
            if (arr[j] > arr[j + 1])
            {
                // 交换元素
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

二、二分法查找

通过调用函数来实现二分法

cpp 复制代码
#include <stdio.h>

// 定义数组长度
#define SIZE 10

// 二分查找函数
int binarySearch(int arr[], int n, int target)
{
    int left = 0;
    int right = n - 1;

    while (left <= right)
    {
        // 计算中间元素的索引
        int mid = left + (right - left) / 2;

        if (arr[mid] == target)
        {
            return mid;
        }
        else if (arr[mid] < target)
        {
            right = mid - 1;
        }
        else
        {
            left = mid + 1;
        }
    }

    return -1; // 如果未找到目标元素,返回 -1
}

int main()
{
    int arr[SIZE] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
    int target;

    // 从控制台输入要查找的目标数字
    printf("请输入要查找的数字:\n");
    scanf("%d", &target);

    // 调用二分查找函数
    int result = binarySearch(arr, SIZE, target);

    if (result!= -1)
    {
        printf("目标数字 %d 在数组中的索引为 %d\n", target, result);
    }
    else
    {
        printf("未找到目标数字 %d\n", target);
    }

    return 0;
}
相关推荐
Doubbbbbbble云2 小时前
基于贪心算法的区间覆盖问题求解策略4
算法·贪心算法
不会就选b8 小时前
算法日常・每日刷题--<贪心>25
数据结构·算法
千里码aicood12 小时前
基于CART算法的图书分类系统设计与实现
数据库·算法·分类
做cv的小昊12 小时前
【World Model】π0.5:a Vision-Language-Action Model with Open-World Generalization
人工智能·算法·机器学习·大模型·多模态·vla·世界模型
لا معنى له13 小时前
World-In-World: World Models in a Closed-Loop World
算法
@yanyu66614 小时前
C编译器安装与第一个C程序
c语言·开发语言
山下梅子酒22514 小时前
洛谷-入门-B2070
c语言
Logic10115 小时前
C语言/数据结构位运算题解:异或XOR找出多任务下载器中的“独特下载速度“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
Discipline102915 小时前
尼泊尔河流流量:天气驱动的预测与高流量风险
人工智能·算法