My program is supposed to read a file, store the records of this file and then sort every record. I'm using an insertion sort algorithm to sort the records, but i'm having some problems making it work.
For example, if the thext file looks like that
string one; string one; string one; 1
string two; string two; string two; 2
string three; stringh three; string three; 3
I need the third record to be the first, the second one to be the second, and the first one to be the last. Since 3>2>1.
I think that the Insertion Sort algorithm is right, since i tested it with a simple array and it's working, but i'm having an hard time implementing it into my program. The error i get is insertionSort’ makes pointer from integer without a cast, i think it's because i'm using a data structure to store the data scanned from the file.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLEN 100
struct Element
{
char one[100];
char two[100];
char three[100];
int st;
};
void insertionSort(int arr[]);
void printArray(int arr[]);
int main() {
int i;
struct Element elements[MAXLEN];
FILE * fpointer = fopen("clients.txt", "r");
char buffer[1024]; // Define a really big string to hold the line of text in
char *field;
int field_number;
while(fgets(buffer,1024,fpointer))
{
field_number=0;
field=strtok(buffer,";");
while(field)
{
switch(field_number)
{
case 0:
strcpy(elements[i].one,field);
break;
case 1:
strcpy(elements[i].two,field);
break;
case 2:
strcpy(elements[i].three,field);
break;
case 3:
elements[i].st=atoi(field);
break;
}
field=strtok(NULL,";"); // Get next field
field_number++;
}
i++; // Move the index for elements to the next one
}
insertionSort(elements[MAXLEN].st);
printArray(elements[MAXLEN].st);
fclose(fpointer);
return 0;
}
void insertionSort(int arr[])
{
struct Element elements[MAXLEN];
int i, key, j;
for (i = 1; i < 10; i++)
{
key = elements[i].st;
j = i-1;
while (j >= 0 && elements[j].st > key)
{
elements[j+1].st = elements[j].st;
j = j-1;
}
elements[j+1].st = key;
}
}
void printArray(int arr[])
{
int i;
for (i=0; i < 10; i++) {
printf("%d ", arr[i]);
printf("\n");
}
}