Search code examples
carraysstructurebubble-sort

Sorting a structure


I wanted to sort this problem in C with something like bubble sort ... anyone can help

  • Implement a list with 5 struct Point (Being this a point w/ X, y);
  • Sort the 5 struct point (first evaluate x then y).

Example:

  // The points 
  p[0]={2,3}
  p[1]={4,5}
  p[2]={1,5}
  p[3]={4,3}
  p[4]={1,2}

  // Should become

  p[0]={1,2}
  p[1]={1,5}
  p[2]={2,3}
  p[3]={4,3}
  p[4]={4,5}

Solution

  • The OP is asking for a C solution, so here you go:

    void bsortDesc(struct yourStruct list[80], int s)
    {
        int i, j;
        struct yourStruct temp;
    
        for (i = 0; i < s - 1; i++)
        {
            for (j = 0; j < (s - 1-i); j++)
            {
                if (list[j].marks < list[j + 1].marks)
                {
                    temp = list[j];
                    list[j] = list[j + 1];
                    list[j + 1] = temp;
                } 
            }
        }
    }
    

    Also, here's what I got it from: here.