I was trying to write a code for:
 read in N numbers from a file FILE1 into an array(dynamic)
then sort those numbers
then search for numbers (1 per line, given in FILE2) in the array.
#include <stdio.h>
 #include <stdlib.h>
#include<math.h>
 #include<string.h>

int main(int argc, char* argv[])
{

FILE *fp1=fopen("myFile1.txt", "r");
if (fp1 == NULL)
{
      printf("cannot open this file");
      exit(0);
}
FILE *fp2 = fopen("test1.txt", "w");
if (fp2 == NULL) 
{
      puts("Not able to open this file");
      exit(1);
}
int i=0,num,j,k;
int *B=NULL;
int *C;
int a;
int size=32;
B = malloc(sizeof(int)*size);
while (fscanf(fp1, "%d", &num) == 1)
{
    if (i<size)
    {

     B[i]=num;
     fprintf(fp2,"%d\r\n",num);
     i++;
    }  
    else
    {
         C = malloc(sizeof(int)*2*size);
         memcpy( C, B, size*sizeof(int)) ;
         free(B);
         B=&C[0];
         B[i]=num;
         i++;
         size=size*2;
         i++;


        for (j=0; j<size; ++j)
        {
          for (k=j+1; k<size; ++k)
          {
            if (B[j] < B[k])
            {
            a= &B[j];
            B[j] = B[k];
            B[k] = a;
            }
         }
      }

       printf ("after sorting");
       for (j=0; j<size; ++j)
           printf ("%d\n", B[j]);

  }


}
return 0;
fclose(fp1);
fclose(fp2);
}
Reading from a file and store into an array(dynamic) part is executed very correctly. But now I am not able   to understand how to sort these numbers. I am trying to apply bubble sort but it will put 0s in my array,     may be I am not implementing it correctly.

Recommended Answers

All 2 Replies

The C Standard Library(stdlib.h) includes qsort which can be used to sort an array. That library also includes a binary search function(bsearch).

The thing about arrays that are dynamically updated (new or changed entries) is that to keep it sorted is expensive. Myself I have resorted usually to using an insertion sort algorithm where when you insert or modify an entry that will change the order it should be in, you do it at that point, and don't bother to sort the entire array. Things to consider are head/tail optimizations where you determine that an entry, or changed entry, will go at the head or tail of the queue. This has been very effective for me. FWIW, the insertion sort algorithm is a version of bsearch. It finds the point where the new/changed entry will go, moves the rest of the elements down one (resizing the array if necessary), and then placing that entry at that point. I will try to post some code to do this tomorrow when I get back from work.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.