Home > Blockchain >  How can I make this code smaller, without 3 loops? I should find 3 students with the smallest marks
How can I make this code smaller, without 3 loops? I should find 3 students with the smallest marks

Time:12-19

I have to make my lab)) In general, I should find the index of three students with the smallest rating points. How I can do it without three loops? Just by one. In this function, I use structures and output arguments.

int addDelateThree(stud** pListHead, int* Imin, int* Jmin, int* Cmin) {
    stud* pTemp = pListHead;
    stud* SpTemp = pListHead;
    stud* TpTemp = pListHead;
    int check = 0;
    double min1 = pTemp->madian;
    double min2 = SpTemp->madian;
    double min3 = pTemp->median;

    int i = 0;
    while (pTemp != NULL) {
        if (min1 > pTemp->madian) {
            min1 = pTemp->madian;
            *Imin = i;
        }
        i  ;
        pTemp = pTemp->next;
    }

    i = 0;
    while (SpTemp != NULL) {
        if (min2 > SpTemp->madian && i != *Imin) {
            min2 = SpTemp->madian;
            *Jmin = i;
        }
        i  ;
        SpTemp = SpTemp->next;
    }

    i = 0;

    while (TpTemp != NULL) {
        if (min3 > TpTemp->madian && i != *Imin && i != *Jmin) {
            min3 = TpTemp->madian;
            *Cmin = i;
        }
        i  ;
        TpTemp = TpTemp->next;
    }
} 

CodePudding user response:

  1. Make a list of 3 stud *. Initialize all to point to a dummy record whose .madian = INFINTY;

  2. Walk the linked list once.

    Compare node's .madian to list[2]->madian. If <=, adjust list of 3 with new minimal .madian. This may involve several compares as code compares 1st the greatest min value, then next greatest min and finally the least value.

  3. Report result.

O(n) solution.

  •  Tags:  
  • c
  • Related