【解決方法】2 つの for ループ ロジックの違いは何ですか。

プログラミングQA


 struct triangle 
{
	int a;
	int b;
	int c;
};

typedef struct triangle triangle1;

void sort_by_area(triangle1* tr, int n)
{
    int i,j,temp;
    int *p=(int *) calloc(100, sizeof(int));
    int *s=(int *) calloc(100, sizeof(int));
    for(i=0;i<n;i++)
    {
        p[i]=(tr[i].a + tr[i].b + tr[i].c) / 2;
        s[i]= p[i] * (p[i]-tr[i].a) * (p[i]-tr[i].b) * (p[i]-tr[i].c);
        s[i]=sqrt(s[i]);
    }

    for(i=0;i<n-1;i++) 
    {
        for(j=0;j<(n-i)-1;j++)
        {
          if(s[j]>s[j+1])
          {
            triangle1 temp_tr = tr[j];
            tr[j] = tr[j+1];
            tr[j+1] = temp_tr;
          }
        }
    }

    free(p);
    free(s);
}

私が試したこと:

I know that the outer loop is used to iterate between the elements of the array and the second one used to compare and swap between the elements, but I cannot understand the logic of the inner loop unlike the outer one which is a basic one and easy for understanding, why j<(n-i)-1??

解決策 1

インデックスするから j + 1 ループ内。
デバッガーでコードを実行し、何が起こるかを観察してください。私の言いたいことがわかるでしょう。

とにかく、それは基本的な宿題の質問であり、コードを書いたのに、なぜそれをまだ理解していないのですか?

解決策 2

これがバブル ソートの仕組みです。たとえば、次のページを参照してください。 Cでのバブルソート | プログラミングの簡素化[^].
ただし、このようなコードには欠陥があります。 たとえば、三角形を交換しても、三角形の領域は交換されません。 さらに、整数に対して切り捨て操作 (除算と平方根) を実行します。
試す

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct Triangle
{
  unsigned a;
  unsigned b;
  unsigned c;
} Triangle;

// compute (4 * squared area) of a triangle
// this way division and square root are avoided while ordering is maintained
unsigned fts_area(Triangle * t)
{
  unsigned p = t->a + t->b + t->c; // perimeter
  unsigned  fts = p * ( p - 2* t->a) * (p - 2 * t->b) * (p - 2 * t->c); // 4 times the squared area
  return fts;
}

void sort_by_area(Triangle tr[], unsigned n)
{
  unsigned * a = (unsigned *) malloc(n * sizeof(unsigned));
  if (! a )
    return; // todo: print an error message

  for (unsigned i=0; i<n; ++i)
  {
    a[i] = fts_area(&tr[i]);
  }

  for( unsigned i=0; i<n-1; ++i)
  {
    for (unsigned j=0; j<(n-i)-1; ++j)
    {
      if(a[j] > a[j+1])
      {
        Triangle temp_tr = tr[j]; // swap the triangles
        tr[j] = tr[j+1];
        tr[j+1] = temp_tr;

        unsigned temp_a = a[j]; // swap their 'areas' as well
        a[j] = a[j+1];
        a[j+1] = temp_a;
      }
    }
  }
  free(a);
}

#define TRIANGLES 4

int main()
{
  Triangle tr[TRIANGLES] = { {2,3,4}, { 100, 42, 80},  { 10, 11, 15}, { 2,2, 3}};


  sort_by_area( tr, TRIANGLES);

  for ( unsigned n = 0; n < TRIANGLES; ++n)
  {
    double area =  sqrt(fts_area(&tr[n])) / 4;
    printf("{ %u , %u, %u }, %g\n", tr[n].a, tr[n].b, tr[n].c, area);
  }

}

コメント

タイトルとURLをコピーしました