my code needs 3 things:
- read numbers file
file1
array (dynamic) - sort numbers
- search numbers input
file2
in sorted 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 file"); exit (0); } file *fp2 = fopen ("test1.txt", "w"); if (fp2 == null) { puts ("not able open file"); exit (1); } int = 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++; (j = 0; j < size; ++j) { (k = j + 1; k < size; ++k) { if (b[j] < b[k]) { = &b[j]; b[j] = b[k]; b[k] = a; } } } printf ("after sorting"); (j = 0; j < size; ++j) printf ("%d\n", b[j]); } } return 0; fclose (fp1); /* note code never reached */ fclose (fp2); }
i complete first part of reading in numbers file. not able understand how sort these numbers.
i trying apply bubble sort, puts 0
s in array. how implementation incorrect?
&
address-of operator. pass pointer. need a = b[i]
, since a
int
.
now sort numbers descending, if want them ascending change <
>
in if (b[j] < b[k])
.
also must always check whether malloc
succeeded or not e.g.:
if (!b) { fprintf(stderr,"b alloc error"); exit(-1); }
also might want consider realloc
.
in addition there built-in qsort
in stdlib.h
, gives better time o(n^2)
.
note: haven't tested file operations, since said work properly.
Comments
Post a Comment