C++ 冒泡排序

本文提供了一个使用C++实现的冒泡排序算法示例,并详细展示了排序过程中的每一轮迭代步骤及最终排序结果。
#include <iostream>
using namespace std;

void my_print(int* pData,int count){
    for(int i=0;i<count;i++){
        cout<<pData[i]<<" ";
    }
    cout<<endl;
}

void BubbleSort(int* pData,int count)
{

    int temp;
    for(int i=1;i<count;i++)
    {
        for(int j=count-1;j>=i;j--)
        {
            if(pData[j]<pData[j-1]){
                temp = pData[j-1];
                pData[j-1]=pData[j];
                pData[j]=temp;
            }
        }

        cout<<"the "<<i<<"round: "<<endl;
        my_print(pData,count);
        cout<<"--------------------------"<<endl;

    }
}


int main(){
    int data[]={10,8,9,7,4,5};
    BubbleSort(data,6);
    cout<<"The sort result:"<<endl;
    my_print(data,6);
    return 0;
}
冒泡排序(Bubble Sort)是一种基础的排序算法,其核心思想是通过多次遍历数组,依次比较相邻元素并在顺序错误时交换它们。尽管冒泡排序在性能上不如更复杂的排序算法(如快速排序或归并排序),但由于其实现简单,它常被用于教学目的或小型数据集的排序。 以下是C++冒泡排序算法的实现示例: ```cpp #include <iostream> using namespace std; void bubbleSort(int arr[], int n) { for (int i = 0; i < n - 1; ++i) { // 每一轮遍历将最大的元素“冒泡”到末尾 for (int j = 0; j < n - i - 1; ++j) { if (arr[j] > arr[j + 1]) { // 交换相邻元素 swap(arr[j], arr[j + 1]); } } } } void printArray(int arr[], int size) { for (int i = 0; i < size; ++i) cout << arr[i] << " "; cout << endl; } int main() { int arr[] = {64, 34, 25, 12, 22, 11, 90}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Original array: "; printArray(arr, n); bubbleSort(arr, n); cout << "Sorted array: "; printArray(arr, n); return 0; } ``` ### 代码说明: 1. **`bubbleSort` 函数**:该函数接受一个整型数组 `arr` 和其长度 `n`,通过嵌套循环实现冒泡排序。外层循环控制排序的轮数,内层循环用于比较相邻元素并进行交换。 2. **优化(可选)**:如果某次遍历中没有发生任何交换,说明数组已经有序,可以提前终止排序过程。这可以提高冒泡排序在最佳情况下的时间复杂度至 O(n)。 3. **`printArray` 函数**:该函数用于打印数组的内容。 4. **`main` 函数**:初始化一个未排序的数组,并调用 `bubbleSort` 函数进行排序,然后输出排序后的数组。 冒泡排序的时间复杂度为 O(n²),其中 n 是数组的长度。由于其效率较低,冒泡排序通常不适用于大规模数据集。然而,它对于初学者理解排序算法的基本原理具有重要意义。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值