用C語言列印陣列中排序後的唯一元素


給定一個整數元素陣列,任務是移除重複值並以排序方式列印唯一元素。

下面是一個數組,它以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

示例

Input: array[] = {4, 6, 5, 3, 4, 5, 2, 8, 7, 0}
Output: 0 2 3 4 5 6 7 8

解釋

所以,為了達到結果,我們將

  • 提取唯一元素並將其儲存到另一個數組array1中。
  • 對array1進行排序。
  • 列印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'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;
}

輸出

如果我們執行上面的程式,它將生成以下輸出。

0 2 3 4 5 6 7 8

更新於:2019年8月22日

471 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.