博客
关于我
C++基础之地址传递+数组冒泡排序实例
阅读量:359 次
发布时间:2019-03-04

本文共 896 字,大约阅读时间需要 2 分钟。

冒泡排序是对数组进行简单排序的一种方法,通过不断交换相邻元素,逐渐将较大的元素排到数组末尾。

在C++代码中,我们可以通过函数实现冒泡排序。以下是完整的代码示例:

#include 
using namespace std;void bubbleSort(int *arr, int length) { for (int i = 0; i < length - 1; i++) { for (int j = 0; j < length - 1 - i; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } }}void printArray(int *arr, int length) { for (int i = 0; i < length; i++) { cout << arr[i] << endl; }}int main() { int arr[] = {2,1,4,3,6,5,8,7,10,9}; int length = sizeof(arr) / sizeof(arr[0]); bubbleSort(arr, length); printArray(arr, length); system("pause"); return 0;}

通过上述代码,我们可以看到实现步骤如下:

  • 定义了一个bubbleSort函数,用于对数组进行排序
  • 定义了一个printArray函数,用于打印排序后的数组
  • main函数中,创建了一个初始数组,并调用了排序和打印函数
  • 最后通过system("pause")暂停程序输出
  • 运行代码可以看到,排序后的结果为:1,2,3,4,5,6,7,8,9,10

    转载地址:http://qyxq.baihongyu.com/

    你可能感兴趣的文章
    Python web自动化测试 —— 文件上传!
    查看>>
    Python Web自动化测试开发环境搭建(附安装包与虚拟机环境)
    查看>>
    python win32api键盘_Python win32api.keybd_event模拟键盘输入
    查看>>
    python Windows显示当前鼠标坐标
    查看>>
    python Workbook 表格宽度
    查看>>
    python | flanker,一个神奇的 Python 库!
    查看>>
    python | flower,一个强大的 Python 库!
    查看>>
    python | funcy,一个超强的 提供函数式编程工具 Python 库!
    查看>>
    python | ggplot,一个超强的 Python 库!
    查看>>
    python | grab,一个强大的 Python 库!
    查看>>
    python | h5py,一个无敌的关于 HDF5 的 Python 库!
    查看>>
    python | huey,一个非常厉害的 任务调度 Python 库!
    查看>>
    python | hypothesis,一个有趣的 Python 库!
    查看>>
    python | Indico,一个超酷的 Python 库!
    查看>>
    python | isort,一个有趣的 自动整理导入语句 的Python 库!
    查看>>
    python | jinja,一个超酷的 Python 库!
    查看>>
    python | joblib,一个强大的 Python 库!
    查看>>
    python | jsonschema,一个实用的 验证 JSON 数据结构 Python 库!
    查看>>
    python | lxml,一个超酷的 关于XML/HTML 文档 Python 库!
    查看>>
    python | mplfinance,一个有趣的金融数据可视化 Python 库!
    查看>>