"Programming Thinking and Practice" 1028. Sorting and deduplication

"Programming Thinking and Practice" 1028. Sorting and deduplication

topic

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-DuZwOJLm-1680880211040) (C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\ image-20230407223048116.png)]

train of thought

Method 1 (the most convenient): sort all the data directly, the same data will be arranged in adjacent positions, and the control output can ensure that the same data is not output.

Method 2 (Bucket sorting): Bucket sorting is to divide the array into a limited number of buckets and then sort each bucket individually. In this question, it is noticed that the maximum data is only 1000, and only need to open an array with a size of 1001, and then The number array that appears is stored as 1, and the number that does not appear is stored as 0. When outputting, output the numbers corresponding to the array that is not 0 in sequence or in reverse order.

Points to note:

The input of a set of data can directly use EOF to judge whether the input is over. If it is multiple sets of data, the string needs to be split.

the code

Method One:

#include<stdio.h>
#include<stdlib.h>

int cmp1(const void *a,const void *b)
{
    
    
	int *m=(int*)a;
	int *n=(int*)b;
	return *m-*n;               //升序 
}

int cmp2(const void *a,const void *b)
{
    
    
	int *m=(int*)a;
	int *n=(int*)b;
	return *n-*m;                       //降序 
}

int main()
{
    
    
	char judge;
	judge=getchar();
	int number[100];
    int i=0;
    while(scanf("%d",&number[i])!=EOF)    //EOF判断一组数据输入结束
    {
    
    
        i++;
    }
	if(judge=='A')
	{
    
    
		qsort(number,i,sizeof(int),cmp1);  
	}
	if(judge=='D')
	{
    
    
		qsort(number,i,sizeof(int),cmp2);
	}
	for(int j=0;j<i;j++)
	{
    
    
		printf("%d ",number[j]);
		while(number[j]==number[j+1])  //相同只输出一个
		{
    
     
			j++;
		}
	}
	return 0; 
}

Law 2:

#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	char judge;
	judge=getchar();
	int tab[1001]={
    
    0};
    int number;
    while(scanf("%d",&number)!=EOF)    //EOF判断一组数据输入结束
    {
    
    
        if(tab[number]==0)
        {
    
    
            tab[number]=1;
        }
    }
	if(judge=='A')
	{
    
    
		for(int j=0;j<1001;j++)
        {
    
    
            if(tab[j]==1)
            {
    
    
                printf("%d ",j);
            }
        } 
	}
	if(judge=='D')
	{
    
    
		for(int j=1000;j>=0;j--)
        {
    
    
            if(tab[j]==1)
            {
    
    
                printf("%d ",j);
            }
        } 
	}
	return 0; 
}

Guess you like

Origin blog.csdn.net/boxueyuki/article/details/130022542