在冒泡排序中使用递归

时间:2020-06-13 10:00:15

标签: c++ algorithm

大家好,我开始学习数据结构和算法,并在学习概念后自行实现了气泡排序。以下是我在理解后编写的代码,但是问题在于它仅运行一个周期,并且没有递归排序。

  • 例如:

{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;
}

2 个答案:

答案 0 :(得分:1)

您的函数按副本使用vector<int>向量,因此在第一次交换之后,仅此副本被发送以进行递归排序。

只需将&添加到您的函数参数vector<int> bubble_sort(vector<int> &vec)中,它就可以正常工作

答案 1 :(得分:0)

如果你想完全实现递归,又不想在代码中使用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);
}
相关问题