【发布时间】:2015-02-10 18:51:34
【问题描述】:
这段代码可能看起来很糟糕,我是一个初学者程序,所以让我的代码更好的提示将有很大帮助。我想知道如何让 bubbleSort() 全局修改数组值?,目前我在 main 中填充了我的数组,它适用于搜索方法,但后来我使用了 bubbleSort(),然后尝试进行搜索和它似乎 bubbleSort() 并没有影响 main 中的数组,而只是将其保留在函数中。我一直在环顾四周,有些地方说我需要 malloc,如果是这样,我将如何修改我的代码以解决这个问题?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
typedef struct {
char name[10][9];
int data[10];
}Word;
void bubbleSort (Word q);
void linearSearch(int num, Word q);
void binarySearch(int num, Word q);
int main (int argc, const char *argv[]){
Word q;
char txtName[9]; /* One extra for nul char. */
int score;
int i = 0;
int m = 0;
FILE *ifp, *ofp;
ifp = fopen("Data.txt", "r");
while (fscanf(ifp, "%8s %d", txtName, &score) == 2) {
strcpy(q.name[i], txtName);
printf ("Name: %s \n", q.name[i], i);
q.data[i] = score;
printf ("Data: %d \n", q.data[i], i);
i++;
}
linearSearch(320, q);
binarySearch(320, q);
bubbleSort(q);
while (m <= 9){
printf("Name: %s, Data: %d \n", q.name[m], q.data[m]);
m++;
}
return EXIT_SUCCESS;
}
void linearSearch(int num, Word q){
int i = 0;
int foundIt = 0;
int numNumbers = 10;
while ((foundIt == 0) && (i <= numNumbers)){
if (num != q.data[i]){
i = i + 1;
} else {
foundIt = 1;
}
}
if (foundIt == 1){
printf("Name found at position %d \n", i + 1);
} else {
printf("Required person not found \n");
}
}
void bubbleSort (Word q){
int last = 9;
int Swapped = 1;
int i = 0;
int m = 0;
char temp[32] = "Hello";
int tempA;
while (Swapped == 1){
Swapped = 0;
i = 0;
while (i < last){
if (q.data[i] > q.data[i+1]) {;
//Copy Name of Element
strcpy (temp, q.name[i]);
strcpy(q.name[i], q.name[i+1]);
strcpy(q.name[i+1] , temp);
//Copy Data of corresponding element
tempA = q.data[i];
q.data[i] = q.data[i+1];
q.data[i+1] = tempA;
Swapped = 1;
}
i = i + 1;
}
last = last - 1;
}
linearSearch(320, q);
}
void binarySearch(int num, Word q){
int Lower = 0;
int Upper = sizeof(&q.data);
int FoundIt = 0;
int PositionFound;
int Middle = 0;
while (FoundIt == 0 || (Lower > Upper) != 0){
Middle = floor((Upper + Lower) / 2);
if (num == q.data[Middle]){
FoundIt = 1;
PositionFound = Middle;
} else {
if (num < q.data[Middle]){
Upper = Middle - 1;
} else {
Lower = Middle + 1;
}
}
}
if (FoundIt == 1){
printf("Name found at position %d \n", PositionFound + 1);
} else {
printf("Required person not found \n");
}
}
输入是:
约翰 32
马克 12
马太福音 29
路加福音 21
伊萨克 24
凯恩 2
瑞恩 5
亚伯 10
亚当 320
夏娃 1
【问题讨论】:
-
欢迎来到 Stack Overflow!请拨打tour 并阅读How to Ask 以了解我们对问题的期望。请不要一次又一次地提出同样的问题。跟进上一个。
-
通过指针传递您的
Word实例。由于您是按值传递,因此修改了您传入的Word实例的副本,原始的保持不变。你不需要一个全局变量。 -
@SouravGhosh 不,这是一个不同的问题,另一个我只是想知道如何交换它们以便它影响全局结构数组?并且我在bubbleSort 中所做的我可以在其他任何地方使用该数组?
-
您需要阅读这些内容并自己解决问题。您需要将函数签名更改为
void bubbleSort (Word* q)。当您调用它时,请使用bubbleSort(&q);,并且在您使用q.的任何地方都需要切换到q->。那只是一个开端。还有其他问题,但是如果您阅读书籍或做教程,您将能够自己识别它们。
标签: c arrays struct malloc global