C でソートされた配列内の固有の要素を出力する

王林
リリース: 2023-09-20 17:05:01
転載
731 人が閲覧しました

整数要素の配列が与えられた場合、タスクは重複する値を削除し、ソートされた方法でさまざまな要素を出力することです。

以下は整数型の値を4、6、5、3、4、5、2、8、7、0の順に格納した配列です。 さて、結果は0になりますが、 2、3、4、4、5、5、6、7、8 はソートされた要素を順番に出力しますが、この結果には重複する値 4 と 5 がまだ含まれているため、それらを削除する必要があり、最終結果は 0 になります。 、2、3、4、5、6、7、8

C でソートされた配列内の固有の要素を出力する

##例

Input: array[] = {4, 6, 5, 3, 4, 5, 2, 8, 7, 0}
Output: 0 2 3 4 5 6 7 8
ログイン後にコピー

説明

つまり、目標を達成するには、

    異なる要素を別の配列 array1 に保存します。
  • 配列1をソートします。
  • array1 の値を出力します。
アルゴリズム

START
   STEP 1: DECLARE VARIABLES i, j, array1[size], temp, count = 0
   STEP 2: LOOP FOR i = 0 AND i < size AND i++
      LOOP FOR j = i+1 AND j < size AND j++
         IF array[i] == array[j]) then,
            break
         END IF
      END FOR
      IF j == size then,
         ASSIGN array1[count++] WITH array[i]
      END IF
   END FOR
   STEP 3: LOOP FOR i = 0 AND i < count-1 AND i++
      LOOP FOR j = i+1 AND j < count AND j++
         IF array1[i]>array1[j] then,
            SWAP array1[i] AND array[j]
         END IF
      END FOR
   END FOR
   STEP 4: PRINT array1
STOP
ログイン後にコピー

#include <stdio.h>
/* Prints distinct elements of an array */
void printDistinctElements(int array[], int size) {
   int i, j, array1[size], temp, count = 0;
   for(i = 0; i < size; i++) {
      for(j = i+1; j < size; j++) {
         if(array[i] == array[j]) {
            /* Duplicate element found */
            break;
         }
      }
      /* If j is equal to size, it means we traversed whole
      array and didn&#39;t found a duplicate of array[i] */
      if(j == size) {
         array1[count++] = array[i];
      }
   }
   //sorting the array1 where only the distinct values are stored
   for ( i = 0; i < count-1; i++) {
      for ( j = i+1; j < count; j++) {
         if(array1[i]>array1[j]) {
            temp = array1[i];
            array1[i] = array1[j];
            array1[j] = temp;
         }
      }
   }
   for ( i = 0; i < count; ++i) {
      printf("%d ", array1[i]);
   }
}
int main() {
   int array[] = {4, 6, 5, 3, 4, 5, 2, 8, 7, 0};
   int n = sizeof(array)/sizeof(array[0]);
   printDistinctElements(array, n);
   return 0;
}
ログイン後にコピー

出力

上記のプログラムを実行するとこれにより、次の出力が生成されます。

えええええ

以上がC でソートされた配列内の固有の要素を出力するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
ソース:tutorialspoint.com
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!