我一直在嘗試撰寫一個名為 sort 的函式,它將函式及其大小作為引數,并使用 C 中的冒泡排序對陣列進行排序。但我的大部分時間都不起作用。這是代碼:
#include<stdio.h>
#include<string.h>
void print(char a[][10], int size);
void sort(char a[][10], int size);
int main(){
int n;
scanf("%d", &n);
char a[n][10];
int i;
for (i = 0; i < n; i ){
scanf("%s", a[i]);
}
print(a, n);
sort(a, n);
print(a, n);
}
void print(char a[][10], int size){
int i;
printf("\n");
for(i = 0; i < size; i ){
printf("%s", a[i]);
printf("\n");
}
}
void sort(char a[][10], int size){
int i, j;
char temp[10];
for(i = 0; i < size; i ){
for(j = 0; j < size - i - 1; j ){
if(strcmp(a[j], a[j 1]) > 0)
strcpy(temp , a[j]);
strcpy(a[j] , a[j 1]);
strcpy(a[j 1], temp);
}
}
}
預期輸入:3 man car dog
預期輸出:car dog man
我得到了什么:dog man man
我上面寫的代碼只有在順序相反的時候才有效(man dog car)。請幫忙。
uj5u.com熱心網友回復:
在此代碼段中:
if(strcmp(a[j], a[j 1]) > 0)
strcpy(temp , a[j]);
strcpy(a[j] , a[j 1]);
strcpy(a[j 1], temp);
您在條件之后缺少花括號。它應該是:
if(strcmp(a[j], a[j 1]) > 0) {
strcpy(temp , a[j]);
strcpy(a[j] , a[j 1]);
strcpy(a[j 1], temp);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/536613.html
標籤:数组C细绳算法排序
