I've written a program to recursively sort an array. However, I get the following error on line 11: syntax error before ']' token.
Here is the code:
//This program recursively sorts an array
#include<stdio.h>
void rec_sort(int values[], int n);
main()
{
int vals[4];
vals[0] = 37; vals[1] = 48; vals[2] = 56; vals[3] = 63;
printf("this array sorted: %x\n", rec_sort(vals[], 4));
system("Pause");
return 0;
}
void rec_sort(int values[], int n) {
//Base case
if (n<2) return;
int maxIndex=0;
int i;
//Find max item in array in indexes 0 through n-1
for(i=1; i<n;i++) {
if(values[i] > values[开发者_StackOverflow社区maxIndex])
maxIndex=i;
}
//Swap this element with one stored in n-1
//Set temp to n-1, set n-1 in array to max, set max to temp
int temp = values[n-1]; //Store temp as last element in array
values[n-1] = values[maxIndex]; //Store last element as max value in array
values[maxIndex] = temp; //temp will keep on changing, as array is sorted
//Recursively sort the array values of length n-1
sort(values, n-1);
}
It looks like you're trying print out the whole array, which C won't do in one call to printf
. Instead, you need a loop to iterate through the array and print out each number individually:
for (i=0; i<4; i++)
printf("%x\n", vals[i]);
Since rec_sort
isn't returning the array, you also need to invoke it separately from the call the printf, so you'd get something like:
// sort the data:
rec_sort(vals, 4);
// print the sorted values:
for (i=0; i<4; i++)
printf("%x\n", vals[i]);
Just remove the []
on line 11. But this is a naive answer to your question, and won't get you far. There are other problems - the most obvious is the idea of printf(..., rec_sort(...)...);
Considering rec_sort
has void
return type, how do you expect printf()
to understand what to do? I am not sure what you want either, but this should be at least a start for you.
printf("this array sorted: %x\n", rec_sort(vals[], 4));
but rec_sort()
is void
. Doesn't return
anything
void rec_sort(int values[], int n)
Also, declare your main as int main()
The problem is in this:
rec_sort(vals[], 4)
What exactly do you want to do there? The []
is an index operation, so either you need to put a number in there, or you leave them out completely (if you want to talk about the whole array).
The first thing you should do is remove the square brackets:
printf("this array sorted: %x\n", rec_sort(vals, 4));
Second, note that rec_sort returns void, so you cant use the return value
you need
int i; // at the top of the main
// ...
rec_sort(vals, 4);
printf("this array sorted: ");
for(i = 0; i < 4; ++i) printf("%x ", vals[i]);
printf("\n");
Third: you need to call rec_sort again
Fourth: what are you tryin to do with the system
statement?
精彩评论