huyuhang-c++-day08

数组作为函数的参数

  • 数组中元素中作为函数的参数
    案例: 统计数组对应元素中大于/小于/等于的个数
#include <iostream>
using namespace std;
int large(int x, int y){
    if (x > y)
        return 1;
    else if (x < y)
        return -1;
    else
        return 0;
}
int main(){
    int a[4] = {2223, 166 , 33 , 55};
    int b[4] = {323, 166 , 3 , 5335};
    int g = 0,  e = 0, l = 0;
    for (int i = 0; i < 4; ++i) {
        int flag = large(a[i], b[i]);
        if (flag == 1)
            g++;
        else if (flag == 0)
            e++;
        else
            l++;
    }
    cout<<" a[i] > b[i] counts "<<g<<endl;
    cout<<" a[i] = b[i] counts "<<e<<endl;
    cout<<" a[i] < b[i] counts "<<l<<endl;

}


案例

  • 编写一个可以控制范围和个数的生成数组函数
  • 编写打印数组的函数
  • 对生成数组传入冒泡排序函数进行排序
  • 对生成数组传入选择排序函数进行排序
#include <iostream>
#include <ctime>
using namespace std;
//- 编写一个可以控制范围和个数的生成数组函数
//- 对生成数组传入冒泡排序函数进行排序
//- 对生成数组传入选择排序函数进行排序
/*
 * arr[] 返回数组
 * a 生成随机数的下限
 * b 生成随机数的上限
 * n 是生成个数
 */
void genrateArray(int arr[], int a, int b, int n){
    srand((unsigned int )time(NULL));
    for (int i = 0; i < n; ++i) {
        //  生成a~b 之间的一个随机整数
        arr[i] = rand() % (b-a+1)+ a;
    }
}
void printArray(int arr[], int len){
    cout << "[";
    for (int i = 0; i < len; ++i) {
       if (i==len-1)
           cout << arr[i] << "]";
       else
           cout << arr[i] << ", ";
    }
    cout <<  endl;
}
void bubbleSort(int arr[], int len){
    for (int i = 0; i < len -1; ++i) {
        for (int j = len-1; j > i; --j) {
            if (arr[j-1] > arr[j]){
                int temp = arr[j-1];
                arr[j-1] = arr[j];
                arr[j] = temp;
            }
        }
    }
}
void selectSort(int arr[], int len){

    for (int i = 0; i < len - 1; ++i) {
        int minIndex = i;
        for (int j = i; j < len; ++j) {
            if (arr[j] < arr[minIndex]){
                minIndex = j;
            }
        }
        // 优化
        if (minIndex!=i){
            int temp = arr[i];
            arr[i] = arr[minIndex];
            arr[minIndex] = temp;
        }
    }
}
int main(){
    const int N = 10;
    int arr[N];
    genrateArray(arr, 1, 100, N);
    cout<<"selectSort Before"<< endl;
    printArray(arr, N);
    selectSort(arr, N);
    cout<<"selectSort After"<< endl;
    printArray(arr, N);
    cout<<"bubbleSort Before"<< endl;
    genrateArray(arr, 1, 1000, N);
    printArray(arr, N);
    cout<<"bubbleSort After"<< endl;
    bubbleSort(arr, N);
    printArray(arr, N);
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值