C++基础练习案例:使用指针、数组和函数,封装一个函数,利用冒泡排序,实现对整型数组的升序排序

题目:
使用指针、数组和函数,封装一个函数,利用冒泡排序,实现对整型数组int arr[] = {4, 2, 8, 0, 5, 7, 1, 3, 9}的升序排序。

解题思路:
1、定义一个函数,函数名为 bubble_sort,传入参数为 int *arr 和 int len,分别表示待排序的整型数组和数组长度。
2、在 bubble_sort 函数内部,利用冒泡排序算法实现升序排序。冒泡排序算法的基本思路是:依次比较相邻的两个元素,如果前一个元素大于后一个元素,则交换它们的位置。一轮比较下来,最大的元素就会“冒泡”到数组的末尾,因此称为“冒泡排序”。
3、实现冒泡排序的代码如下:

void bubble_sort(int *arr, int len) {
    int i, j, temp;
    for (i = 0; i < len - 1; i++) {
        for (j = 0; j < len - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

4、在主函数中定义一个整型数组,并赋初值,调用 bubble_sort 函数进行排序,然后输出排序结果。
5、主函数的代码如下:

#include<iostream>
using namespace std;

void bubble_sort(int *arr, int len);

int main() {
	int arr[9] = { 4, 2, 8, 0, 5, 7, 1, 3, 9 };
	int len = sizeof(arr) / sizeof(arr[0]);

	cout << "排序前:" << endl;
	for (int i = 0; i < len; i++) {
		cout << arr[i] << " ";
	}
	cout << endl;

	bubble_sort(arr, len);

	cout << "排序后:" << endl;
	for (int i = 0; i < len; i++) {
		cout << arr[i] << " ";
	}
	cout << endl;

	return 0;
}

6、将以上代码保存为一个文件,编译运行即可得到排序后的结果。

以下是使用指针、数组和函数实现整型数组升序排序的总代码:

#include<iostream>
using namespace std;

void bubble_sort(int *arr, int len);

int main() {
	int arr[9] = { 4, 2, 8, 0, 5, 7, 1, 3, 9 };
	int len = sizeof(arr) / sizeof(arr[0]);

	cout << "排序前:" << endl;
	for (int i = 0; i < len; i++) {
		cout << arr[i] << " ";
	}
	cout << endl;

	bubble_sort(arr, len);

	cout << "排序后:" << endl;
	for (int i = 0; i < len; i++) {
		cout << arr[i] << " ";
	}
	cout << endl;

	return 0;
}

void bubble_sort(int *arr, int len) {
	for (int i = 0; i < len - 1; i++) {
		for (int j = 0; j < len - 1 - i; j++) {
			if (arr[j] > arr[j + 1]) {
				int temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Make_magic

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值