Reputation: 11
I'm a beginner to programming and I'm working through K.N.King's "C Programming: A Modern Approach". Right now I'm trying to do programming project 1 of chapter 9 but I keep getting a segfault and I'm not sure what's wrong with the code. Any correction is appreciated!
These are the instructions:
Write a program that asks the user to enter a series of integers (which it stores in an array), then sorts the integers by calling the function selection_sort. When given an array with n elements, selection_sort must do the following:
1. Search the array to find the largest element, then move it to the last position in the array.
2. Call itself recursively to sort the first n - 1 elements of the array.
And this is my code:
#include <stdio.h>
void selection_sort(int n, int a[n]);
int main(void)
{
int n;
printf("Number of integers to sort: ");
scanf("%d", &n);
int a[n];
printf("Enter the integers: ");
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
selection_sort(n, a);
printf("Sorted array: ");
for (int i = 0; i < n; i++)
printf("%d", a[i]);
return 0;
}
void selection_sort(int n, int a[n])
{
int swap, max = a[n - 1];
for (int i = 0; i < n; i++) {
if (a[i] > max) {
max = a[i];
swap = a[n - 1];
a[n - 1] = max;
a[i] = swap;
}
}
if (n > 1)
selection_sort(n - 1, a);
}
EDIT: changed while (n > 1) to if (n > 1) and now it works perfectly. But why wouldn't it work with while?
Upvotes: 1
Views: 83
Reputation: 7542
You need to have some base condition for recursion to avoid endlessly calling the same function.You can do something like
void selection_sort(int n, int a[])
{
if(n<=0)return; //base condition
int swap, max = a[n - 1];
Upvotes: 2
Reputation: 41686
You need a condition for not calling selection_sort
. As it is now, your selection_sort
always calls selection_sort
, which results in an endless loop.
And, since you decrement n
at each step, at one point it becomes negative, and you start accessing a[-1]
, which is wrong.
Upvotes: 3