作为我编程课作业的一部分,我一直在编写 C 中的递归快速排序代码。我已经编写了所有内容,但是当我编译时出现以下错误:
- 1>quick_sort.c(32): error C2143: syntax error : missing ';' before 'type'
- 1>quick_sort.c(33): error C2143: syntax error : missing ';' before 'type'
- 1>quick_sort.c(35): error C2065: 'right' : undeclared identifier
- 1>quick_sort.c(36): error C2065: 'pivot' : undeclared identifier
- 1>quick_sort.c(39): error C2065: 'right' : undeclared identifier
- 1>quick_sort.c(39): error C2065: 'pivot' : undeclared identifier
- 1>quick_sort.c(40): error C2065: 'right' : undeclared identifier
- 1>quick_sort.c(42): error C2065: 'right' : undeclared identifier
这是我的代码:
/*This code will take input for 10 integers given by the user
into an array and then sort them with a recursive quicksort
function and then print the updated array. */
#include <stdio.h>
#define ARRSIZE 10
void partition (int arr[],int size);
void val_swap (int a, int b);
int main (void){
int arr[ARRSIZE], left, right, i = 0;
while(i<ARRSIZE){
printf("\nInteger value %d:", i+1);
scanf("%d", &arr[i]);
i++;
}
left = 0;
right = ARRSIZE - 1;
partition(arr, right-left, left);
printf("\nThis is your updated array:");
printf("\n{");
for(i=0; i<ARRSIZE; i++){
printf("%d,", arr[i]);
}
printf("}");
return 0;
}
void partition (int arr[],int size, int left){
if(size < 2){
return;
}
int pivot = size/2;
int left = 0, right = size;
while(left < right){
while(arr[left] < arr[pivot]){
left++;
}
while(arr[right] > arr[pivot]){
right++;
}
val_swap(arr[left], arr[right]);
}
partition(arr,left, 0);
partition(arr, size-left, left+1);
}
void val_swap (int a, int b){
int temp = b;
b = a;
a = temp;
}
有没有人有什么建议?
编辑:好的,我修复了所有错误,其中很多是由于视觉工作室很愚蠢。我的代码现在可以正常工作了,比如当我输入数字 1-10 作为从 10 开始的输入并倒数到 1 时,该功能就起作用了。但是,一旦我给了它更复杂的数字,它只能正确排序大约一半的数组。
这是我更新的代码:
/*This code will take input for 10 integers given by the user
into an array and then sort them with a recursive quicksort
function and then print the updated array. */
#include <stdio.h>
#define ARRSIZE 10
void partition (int arr[],int size, int left);
void val_swap (int *a, int *b);
int main (void){
int arr[ARRSIZE], left, right, i = 0;
while(i<ARRSIZE){
printf("\nInteger value %d:", i+1);
scanf("%d", &arr[i]);
i++;
}
left = 0;
right = ARRSIZE - 1;
partition(arr, right-left, left);
printf("\nThis is your updated array:");
printf("\n{");
for(i=0; i<ARRSIZE; i++){
printf("%d,", arr[i]);
}
printf("}");
}
void partition (int arr[],int size, int left){
int pivot, right;
pivot = size/2;
right = size;
if(size < 2){
return;
}
while(left < right){
while(arr[left] < arr[pivot]){
left++;
}
while(arr[right] > arr[pivot]){
right--;
}
val_swap(&arr[left], &arr[right]);
}
partition(arr,left, 0);
partition(arr, size-left, left+1);
}
void val_swap (int *a, int *b){
int temp = *b;
*b = *a;
*a = temp;
}
还有什么建议吗?