簡體   English   中英

C++中的冒泡排序算法

[英]Bubble Sorting Algorithm in C++

我正在嘗試將冒泡排序算法實現為整數數組,對數組進行排序的 function 將數組作為參數並假設返回排序后的數組。

這是代碼:

#include <iostream>

using namespace std;
int* BubbleSort(int data[]){

for(int i=0; i<sizeof(data)/sizeof(data[0])-1; i++){
    for(int j=0; j<sizeof(data)/sizeof(data[0])-1-i; j++){
         if(data[j+1]>data[j]){
            int temp = data[j+1];
            data[j+1]=data[j];
            data[j]=temp;
        }
    }
}
return data;
}

int main()
{
    int data[]={8,4,9,7,6,5,13,11,10};
    int *a=BubbleSort(data);
    cout<<"{";
    for(int i=0; i<sizeof(data)/sizeof(data[0]); i++){
        cout<<a[i];
        if(i==sizeof(data)/sizeof(data[0])-1){
        cout<<"}"<<endl;
        }else{
        cout<<",";
        }
    }

   return 0;
}

我得到的 output:{8,4,9,7,6,5,13,11,10}

您必須傳遞數組的大小,因為它decays到指向其第一個元素(元素0)的指針。

void BubbleSort(int data[], int size){

    for(int i(0); i != size; ++i){
         for(int j(i + 1); j != size; ++j){
             if(data[i] > data[j]){
                  int temp = data[i];
                  data[i] = data[j];
                  data[j] = temp;
          }
     }    
}

也許為時已晚,但也許將來會有用,

嘗試使用此代碼


...

/**
* Sort array of integers with Bubble Sort Algorithm
*
* @param arr   Array, which we should sort using this function
* @param arrSZ The size of the array
* @param order In which order array should be sort
*
* @return Sorted array of integers
*/
void bubbleSortInt(double arr[], int arrSz, string order = "ascending")
{
    for (int i = 0; i < arrSz; ++i)
    {
        for (int j = 0; j < (arrSz - i - 1); ++j)
        {
            // Swapping process
            if ((order == "descending") ? arr[j] < arr[j + 1] : arr[j] > arr[j + 1])
            {
                swap(arr[j], arr[j + 1]);
            }
        }
    }
    return; // Optional because it's a void function
}// end bubbleSortInt

...

然后在你的主 function 中使用它,如下所示,


...

double integers[array_size];
const int array_size = 10;
string order = "ascending";
bubbleSortInt(integers, array_size, order)
for (int i = 0; i < array_size; ++i)
{
    cout << integers[i] << "\t";
}

...

詳細看一下冒泡排序算法-> https://github.com/teamroyalcoder/algorithms#bubble-sort-algorithm


這是一個 GitHub 存儲庫,您將在其中找到一堆算法,其中包含完整的詳細信息和用c++ https://github.com/teamroyalcoder/algorithms編寫的源代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM