问题:编写一个程序实现筛除数组中重复元素功能。
算法思路:基于简单的想法,先把数组排序,然后扫描整个数组跳过重复的元素。算法的效率取决于排序算法的效率。
算法实现:
//
// main.cpp
// MyProjectForCPP
//
// Created by labuser on 11/2/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#include <iostream>
void sort(int[],int);
void unique(int x[],int n,int *number){
int i;
sort(x, n);
*number=1;
for(i=1;i<n;++i){
if (x[i]!=x[i-1]) {
x[(*number)++] = x[i];
}
}
}
void sort(int x[],int n){
int i,j,temp;
for (i=0; i<n; ++i) {
for (j=i+1; j<n; ++j) {
if (x[i]>x[j]) {
temp=x[i];
x[i]=x[j];
x[j]=temp;
}
}
}
}
int main (int argc, const char * argv[])
{
int x[] = {100, 37, 100, 37, 15, 111,
37, 15, 111, 98, 100,98 };
int n = sizeof(x)/sizeof(int);
int number;
int i;
printf("\nElement Uniquness Program");
printf("\n=========================");
printf("\n\nOriginal Array :");
for (i=0; i<n; i++) {
printf("%4d",x[i]);
}
unique(x, n, &number);
printf("\n\nProcessed Array :");
for (i=0; i<number; i++) {
printf("%4d",x[i]);
}
printf("\n\n");
return 0;
}
运行结果:
Element Uniquness Program
=========================
Original Array : 100 37 100 37 15 111 37 15 111 98 100 98
Processed Array : 15 37 98 100 111
Program ended with exit code: 0