Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my logic incorrect for my selection sort recursion program?

Tags:

c

So my recursion selection sort calls two functions max_index and the swap and at the same time it should recursively swap the stuff, but for some reason it seems to break and explode into fire for certain arrays like the one I have set in main. Does anyone know why this is so? Can someone explain and show me why this isn't working?

int max_index(int arr[], int start, int end)
{
    if ( start >= end ) {
        return 0;
    }
    else if ( end - start == 1 ) {
        return start;
    }
    else {
        int greatest = max_index(arr, start + 1, end);
        if( arr[start] > arr[greatest])
        {
            return start;
        }
        else
        {
            return greatest;
        }

    }
}
void swap(int arr[], int i, int j) {
        int temp;
        temp = arr[i];
    arr[i]=arr[j];
    arr[j]=temp;
}

void rec_ssort(int arr[], int len) {
        int start = 0;
        int last = len - 1;
        //int n = len;
        int maxindex = max_index(arr, start, last);
        //if(arr[maxindex]>0 || arr[maxindex]<n)
        {
            if(arr[maxindex]>arr[last])
            {
                swap(arr, maxindex, last);
                return rec_ssort(arr, last);
            }
            if(arr[maxindex] == arr[last])
            {
                return rec_ssort(arr, last);
            }
         }
}



int main(void)
{
    int i = 0;
    int arr[7] = {2,3,4,1,5,6,7};
    int start = 0;
    int end = 7;
    int stuff = 5;
    rec_ssort(arr, end);
    for(i = 0; i<7; i++)
    printf("%d\n", arr[i]);
}
like image 836
BeginnerC Avatar asked Dec 11 '25 00:12

BeginnerC


1 Answers

All recursive methods need a base case (to exit the recursion). Additionally it helps if you can see progress on the recursion happening at every step. Note that you weren't recursing when the maxindex pointed to a value less than last.

This is one way to correct your issues in rec_ssort:

void rec_ssort(int arr[], int len) {
  // base case: if we're looking at an empty array we're done.
  if (len <= 0) return;

  int last = len - 1;
  int maxindex = max_index(arr, 0, last);
  if (arr[maxindex] > arr[last]) {
    swap(arr, maxindex, last);
  } 

  // recursively call with a shorter len
  rec_ssort(arr, last);
}
like image 50
Nate Avatar answered Dec 12 '25 13:12

Nate



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!