冒泡排序思想:相邻的两个数据两两比较,然后按顺序排出
代码展示1:
#include<stdio.h>
void sort(int arr1[],int sz) {
for (int i = 0; i < sz-1; i++)
{
for (int j = i+1; j < sz; j++)
{
if (arr1[i] > arr1[j]) {
int temp = 0;
temp = arr1[i];
arr1[i] = arr1[j];
arr1[j] = temp;
}
}
}
}
int main() {
int arr[10] = { 9,8,7,4,3,5,2,0,1,6 };
int ArrLength = sizeof(arr) / sizeof(arr[0]);//求数组长度,即包含几个数据
sort(arr,ArrLength);
for (int i = 0; i < ArrLength; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
代码展示2(形参的另一种表示方式):
#include<stdio.h>
void sort(int* arr1,int sz) {//这里的参数以指针的形式也可以
for (int i = 0; i < sz-1; i++)
{
for (int j = i+1; j < sz; j++)
{
if (arr1[i] > arr1[j]) {
int temp = 0;
temp = arr1[i];
arr1[i] = arr1[j];
arr1[j] = temp;
}
}
}
}
int main() {
int arr[10] = { 9,8,7,4,3,5,2,0,1,6 };
int ArrLength = sizeof(arr) / sizeof(arr[0]);//求数组长度,即包含几个数据
sort(arr,ArrLength);
for (int i = 0; i < ArrLength; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
错误代码展示:
#include<stdio.h>
void sort(int* arr1) {
int ArrLength = sizeof(arr1) / sizeof(arr1[0]);//想在这求求数组长度,即包含几个数据
for (int i = 0; i < ArrLength-1; i++)
{
for (int j = i+1; j < ArrLength; j++)
{
if (arr1[i] > arr1[j]) {
int temp = 0;
temp = arr1[i];
arr1[i] = arr1[j];
arr1[j] = temp;
}
}
}
}
int main() {
int arr[10] = { 9,8,7,4,3,5,2,0,1,6 };
sort(arr);
for (int i = 0; i < 9; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
结果展示:
综上三个代码我们可以提出以下问题?
1.在sort函数中求数组长度为什么不可以结果会出错?但在主函数中就可以
2.函数参数传的是什么?是整个数组还是数组首元素地址