博客
关于我
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/

    你可能感兴趣的文章
    Qt笔记——布局管理三件套分割窗口、停靠窗口和堆栈窗口
    查看>>
    poj 3277 线段树
    查看>>
    POJ 3349 Snowflake Snow Snowflakes
    查看>>
    POJ 3411 DFS
    查看>>
    poj 3422 Kaka's Matrix Travels (费用流 + 拆点)
    查看>>
    Qt笔记——官方文档全局定义(二)Functions函数
    查看>>
    POJ 3468 A Simple Problem with Integers
    查看>>
    poj 3468 A Simple Problem with Integers 降维线段树
    查看>>
    poj 3468 A Simple Problem with Integers(线段树 插线问线)
    查看>>
    poj 3485 区间选点
    查看>>
    poj 3518 Prime Gap
    查看>>
    poj 3539 Elevator——同余类bfs
    查看>>
    Qt笔记——官方文档全局定义(三)Macros宏
    查看>>
    poj 3628 Bookshelf 2
    查看>>
    Qt笔记——官方文档全局定义(一)Types数据类型
    查看>>
    POJ 3670 DP LIS?
    查看>>
    POJ 3683 Priest John's Busiest Day (算竞进阶习题)
    查看>>
    POJ 3988 Selecting courses
    查看>>
    POJ 4020 NEERC John's inversion 贪心+归并求逆序对
    查看>>
    poj 4044 Score Sequence(暴力)
    查看>>