Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct {
- unsigned char *pref_name;
- unsigned int poplation;
- } pref_t;
- static pref_t *init_pref(void) {
- pref_t *p = (pref_t *) malloc(sizeof(pref_t));
- p->pref_name = (unsigned char *) malloc(BUFSIZ);
- return p;
- }
- static void print_pref(pref_t **data, size_t len) {
- for (int i = 0; i < len; i++) {
- printf("%s %d\n", data[i]->pref_name, data[i]->poplation);
- }
- }
- static void insert_sort_pref(pref_t **data, size_t len) {
- for (int i = 1; i < len; i++) {
- pref_t *p = data[i];
- if (data[i - 1]->poplation > p->poplation) {
- int j = i;
- do {
- data[j] = data[j - 1];
- j--;
- } while (j > 0 && data[j - 1]->poplation > p->poplation);
- data[j] = p;
- }
- }
- }
- int main(int argc, char **argv) {
- FILE *in;
- if (argc > 1) in = fopen(argv[1], "r");
- else in = stdin;
- char header[BUFSIZ];
- fgets(header, BUFSIZ, in); // ignore header
- pref_t *data[BUFSIZ];
- size_t len = 0;
- for (int i = 0; i < BUFSIZ; i++) {
- data[i] = init_pref();
- if (fscanf(in, "%s%d", data[i]->pref_name, &(data[i]->poplation)) == EOF) {
- len = i;
- break;
- }
- }
- fclose(in);
- printf("Before:\n");
- print_pref(data, len);
- printf("\n");
- insert_sort_pref(data, len);
- printf("After:\n");
- print_pref(data, len);
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement