I am trying to write a function by the name of selection_sort
. This function should, when presented with an array of n integers, search the array to find the largest element then move it to the last position of the array. Once it has done this it should call itself recursively to sort the first n-1 elements of the array.
Here is my code:
#include <stdio.h>
void selection_sort(int [], int);
int main(void)
{
int n, a[n];
printf("How many numbers do you wish to sort? ");
scanf("%d", &n);
printf("Well go on, type them in... ");
for(int i = 0; i < n; i++)
scanf("%d", &a[i]);
selection_sort(a, n);
printf("Here is the sorted array: ");
for(int i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
void selection_sort(int a[], int n)
{
if(n == 1) return;
int temp, largest = 0;
for(int i = 1; i < n; i++) {
if(a[i] > a[largest])
largest = i;
}
temp = a[largest];
a[largest] = a[n-1];
a[n-1] = temp;
selection_sort(a, n-1);
}
When I run this code I get segmentation fault: 11. It doesn't look like any part of my code is going out of the boundaries of the array. I understand that an array of length n is indexed from 0 to n-1. What is going on?