数组作为函数的参数
- 数组中元素中作为函数的参数
案例: 统计数组对应元素中大于/小于/等于的个数
#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;
void genrateArray(int arr[], int a, int b, int n){
srand((unsigned int )time(NULL));
for (int i = 0; i < n; ++i) {
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);
}