简体   繁体   中英

Bubble sort using recursive function in C

When I call my bubble sort recursive function, the array is not getting sorted.

#include"stdio.h"
void bubble(int *arr,int n,int vidx){
if(n==0)
    return;
if(vidx == n)
    bubble(arr,n-1,0);
    return;
if(*(arr+vidx) > *(arr+vidx+1)){
    int temp = *(arr+vidx);
    *(arr+vidx) = *(arr+vidx+1);
    *(arr+vidx+1) = temp;
    bubble(arr,n,vidx+1);
    return;
    }
 } int main(){
      int a[] = {5,4,3,2,1};
      bubble(&a,5,0);
      for(int i = 0 ; i < 5 ; i++)
         printf("%d,",a[i]);
      return 0; }

Actual Output : 5,4,3,2,1,

Expected Output : 1,2,3,4,5,

if(vidx == n)
    bubble(arr,n-1,0);
    return;

This is why I advocate always using braces. As-is, that code is equivalent to:

if(vidx == n){ bubble(arr,n-1,0); }
return;

Most of the body of the bubble function is unreachable.

Edit: Incidentally, I notice two other bugs in what's left:

  • vidx can go up to the length of the array, so vidx+1 will index past the end, which could cause problems
  • When you hit two adjacent elements that are in the right order with respect to each other (ie *(arr+vidx) <= *(arr+vidx+1) ), you make it to the end of the function without recursing further, stopping the sort prematurely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM