簡體   English   中英

在冒泡排序中使用遞歸

[英]Using recursion in bubble sort

大家好,我開始學習數據結構和算法,並在學習了概念后自己實現了冒泡排序。 以下是我根據自己的理解編寫的代碼,但問題是它只運行一個周期並且不會遞歸排序。

  • 例如:

{ 5,1,4,2,8} 排序一次 -> {1,4,2,5,8,}

可能是什么問題?

vector<int> bubble_sort(vector<int> vec){
 int temp = 0;

 for(int i = 0; i < vec.size()-1; i++){    
      temp = vec.at(i+1);                    // holds the adjacent element.

// the following loop swaps the adjacent elements if the previous one is big
            if(vec.at(i) > vec.at(i+1)){
                      vec.at(i+1) = vec.at(i);
                      vec.at(i) = temp;
            }     
           temp = 0;
      }


 for(int i = 0; i < vec.size()-1; i++){         
        if(vec.at(i) > vec.at(i+1)){
            bubble_sort(vec);  
        }     
  }

return vec;
}

您的 function 逐個復制一個vector<int>向量,因此在第一次交換之后,只有這個副本被發送到遞歸排序。

只需將&添加到您的 function 參數中: vector<int> bubble_sort(vector<int> &vec)它應該可以工作

如果您想完全實現遞歸並且不想在代碼中使用 for 循環,請按照此示例進行操作。 這會很有幫助。

#include <iostream>
using namespace std;
/* Function to print an array */
void printArray(int arr[], int n)
{
    for (int i=0; i <= n; i++)
        cout<<arr[i];
}

void bubble_sort_recursive(int arr[], int j, int n) {
   
   // base case 
    if (n==0 || j>n){
        return;
    }
    
    // single pass has been completed and the higher element moved to right for that subarray
    // now call the recursive function by keeping aside the already sorted positioned element
    //i.e next pass wil start from this call
    if (j == n){
            bubble_sort_recursive(arr,0,n-1);
    }

    // swap consecutive 2 elements - main basic of bubble sort
    if (arr[j]>arr[j+1]){
        int t = arr[j];
        arr[j] = arr[j+1];
        arr[j+1] =t;
    }
    // go forward for next element of a single pass
    bubble_sort_recursive(arr,j+1,n);
}


int main() {
    int arr[] = {5,4,3,2,1};
    // get the length of array
    int n = sizeof(arr)/sizeof(arr[0]);
    // call from 0 to len-1 as index starts from 0
    bubble_sort_recursive(arr,0,n-1);
    // print the sorted array
    cout<<"Sorted array:"<<endl;
    printArray(arr, n-1);
}

暫無
暫無

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

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