实例四十三:数组压缩问题
问题描述:
将无序数组压缩成不重复的有序数组,即去掉元数组中的重复出现的元素,并将补重复的元素按照从小到大顺序存储在原数组中。
Compressing an unordered array into a non-repeating ordered array removes the recurring elements from the meta array and stores the repeated elements in the original array in ascending order.
算法思路:
采用插入排序算法,先将 a[0] 作为已完成压缩排序的序列,然后将 a[1] 与 a[0] 比较,若 a[1] 小于 a[0] 则将 a[1] 插入 a[0] 之前:若 a[1] 与 a[0] 相等,无需插入,再将 a[2] 作为待排元素,如此继续…假如 a[0],a[1],…a[k-1] 是已经完成压缩排序的序列,a[i] 是待排元素,则需要将 a[i] 依次与 a[0],a[1],…a[k-1] 进行比较,若发现有相同的元素时无需插入,继续将 a[i+1] 作为待排元素进行处理;若发现比 a[i] 大的元素,则将 a[i] 插入到此元素之前;若既没有发现比它大的也没发现相同的元素,则将 a[i] 插入到序列的最后。
Using the insert sorting algorithm, first a[0] is the sequence of the completed compression sorting, then compare a[1] with a[0], if a[1] is less than a[0] then insert a[1] into a [0] Before: If a[1] is equal to a[0], no insertion is required, then a[2] is used as the element to be discharged, so continue…if a[0], a[1], …a[k-1] is a sequence that has completed compression sorting, a[i] is a to-be-arranged element, then a[i] needs to be followed by a[0], a[1],…a[ K-1] For comparison, if it is found that there is no need to insert the same element, continue to treat a[i+1] as the element to be sorted; if it finds an element larger than a[i], insert a[i] Before this element; if neither finds it nor finds the same element, insert a[i] at the end of the sequence.
/*实例四十三:数组压缩问题*/
#include <stdio.h>
#define N 50
int main(void)
{
int a[N],n,i,k,j,l,t,flag;
printf("Please enter the number of elements in an uncompressed unordered array:\n");
scanf("%d",&n);
printf("Please enter the %d elements separately:\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
i=1; k=1;
while(i<n)
{
flag=0;
for(j=0;j<k;j++)
{
if(a[i]==a[j])
{flag=1; break;}
if(a[i]<a[j])
{
t=a[i];
for(l=k-1;l>=j;l--)
a[l+1]=a[l];
a[j]=t;
k++;
flag=1;
break;
}
}
if(flag==0)
{
a[k]=a[i];
k++;
}
i++;
}
printf("The original array is compressed into an ordered array of %d elements:\n",k);
for(i=0;i<k;i++)
printf("%d ",a[i]);
printf("\n");
return 0;
}