Hey. It's my first post. I decided to register here because i started learning C some months ago but it's not easy without some help. So i hope this will help my learning and i can also contribute to the forums later.
In this exercise i had to use Linear Search on a file with data of students, it had id, name and mark. Here is the code i used. It does the job but i'd like to know simpler solutions for this. Sorry for the language, i should start writing everything in english now.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define numtestes 100
void Trocar (int *a, int *b)
{
int aux;
aux = *a;
*a = *b;
*b = aux;
}
int DeterminarPivot (int V[], int inicio, int fim)
{
int i, k = inicio; // k = posição do pivot V[inicio]
for (i = inicio+1; i <= fim; i++)
if (V[i] < V[inicio])
{
k++;
Trocar (&V[i], &V[k]);
}
Trocar (&V[inicio], &V[k]);
return (k);
}
void OrdenarQuicksort(int V[], int inicio, int fim)
{
int k; // k = pos ição do pivot V[inicio]
if (inicio < fim)
{
k = DeterminarPivot (V, inicio, fim);
OrdenarQuicksort (V, inicio, k-1);
OrdenarQuicksort (V, k+1, fim);
}
}
int PesquisaSequencial(int Num, int v[], int tam)
{
int i=0;
while((i<tam) && (v[i]<Num))
i++;
if((i<tam) && (Num==v[i]))
return i;
else
return -1;
}
typedef struct
{
int numero;
char nome[100];
float nota;
}DADOS;
int main()
{
DADOS testes[numtestes];
int N=0;
char auxnum[100];
char auxnota[100];
FILE *f;
f=fopen("C:\\Users\\PC\\Documents\\dados5.txt", "r");
if(f==NULL)
{
printf("Erro\n");
return 0;
}
while(fgets(auxnum, 100, f)!=NULL)
{
testes[N].numero=atoi(auxnum);
fgets(testes[N].nome, 100, f);
fgets(auxnota, 100, f);
testes[N].nota=atof(auxnota);
N++;
}
printf("Foram lidos %d alunos\n", N+1);
int notas_2[100];
for(int i=0;i<100;i++)
{
notas_2[i]=testes[i].numero;
}
DeterminarPivot(notas_2, 0, 65);
OrdenarQuicksort(notas_2, 0, 65);
int indicenum = PesquisaSequencial(3121791, notas_2, 66);
printf("resultado encontra-se no indice %d\n", indicenum);
printf("Indice 15 corresponde ao numero %d\n", notas_2[15]);
}