Yesterday I came across a recursive implementation of bubble sort, which looks elegant at first glance:
template <class T> void bubblesort_recursive(T data[], const int n){
if(n==1) return;
else{
bubblesort_recursive(data+1, n-1);
if(data[1]<data[0]) swap(data[1],data[0]);
bubblesort_recursive(data+1, n-1);
}
}
However, I soon realized that it calls the recursive case twice and the time recursive relation for its time complexity seems to be following T(n)=2T(n-1)+c, which leads to exponential time complexity. However, bubble sort usually leads to n^2 time complexity. Is my analysis somewhere wrong or is this just an inefficient implementation of bubble sort? If it was the latter one, how could it be improved?