How to delete duplicate elements in an array in C language?

In the C programming language, you can eliminate duplicate elements from an array using the following method:

  1. Firstly, sort the elements in the array to group the duplicate elements together.
  2. Create a new array to store the array after removing duplicate elements.
  3. Iterate through the sorted array and copy the first element into a new array.
  4. Traverse through the sorted array and copy any element to the new array if it is different from the last element in the new array.
  5. Finally, the new array will store the array after removing duplicate elements.

Here is a sample code.

#include <stdio.h>

void removeDuplicates(int arr[], int n) {
    // 对数组进行排序
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }

    // 创建新数组,用于存放删除重复元素后的数组
    int newArr[n];
    int j = 0;
  
    // 遍历排序后的数组,将第一个元素复制到新数组中
    newArr[j++] = arr[0];

    // 遍历排序后的数组中的其他元素,将不重复的元素复制到新数组中
    for (int i = 1; i < n; i++) {
        if (arr[i] != newArr[j - 1]) {
            newArr[j++] = arr[i];
        }
    }

    // 打印删除重复元素后的数组
    printf("删除重复元素后的数组为:\n");
    for (int i = 0; i < j; i++) {
        printf("%d ", newArr[i]);
    }
    printf("\n");
}

int main() {
    int arr[] = {1, 2, 3, 4, 4, 5, 6, 6, 6, 7};
    int n = sizeof(arr) / sizeof(arr[0]);

    removeDuplicates(arr, n);

    return 0;
}

Running the code above will output: The array after removing duplicate elements is: 1 2 3 4 5 6 7.

bannerAds