给定一个整数元素的数组,任务是删除重复的值并以排序的方式打印出不同的元素。
下面给出了一个以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 array1stop
示例#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
以上就是在c语言中,打印已排序的数组中的不重复元素的详细内容。