天天看点

字符数组的排序

我感觉字符数组的排序可以把字符数组以及指针这一概念讲述的比较清楚明白。

看程序:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
int get_line(char *line[]);
void sort(char *p[],int n);
void print_string(char *p[],int n);
char *line[25];
int main()
{
	int number_of_line;
	number_of_line = get_line(line);
	if (number_of_line<0)
	{
		printf("memory location error!\n");
		exit(-1);
	}
	sort(line,number_of_line);
	print_string(line,number_of_line);
	system("pause");
	return 0;
}

int get_line(char *line[])
{
	int n=0;
	char buffer[80];
	puts("please input a string:\n");
	while(n<25&&gets(buffer)!=0&&buffer[0]!='\0')
	{
		if ((line[n] = (char *)malloc(strlen(buffer)+1))==NULL)
			return -1;
		strcpy(line[n++],buffer);
	}
	return n;
}
void sort(char *p[],int n)
{
	char *temp;
	for (int i=0;i<n-1;i++)
	{
		for (int j=i+1;j<n;j++)
		{
			if (strcmp(p[i],p[j])>0)
			{
				temp = p[i];
				p[i] = p[j];
				p[j] = temp;
			}
		}
	}
}

void print_string(char *p[],int n)
{
	for (int i=0;i<n;i++)
	{
		puts(p[i]);
	}
}
           

代码本身没有太多的可讲的地方,将get_line()函数看清楚,是比较好的!!

下午的是,觉得还是把上面的程序稍微加一点,加上一个函数指针的概念在上面,还是非常简单,我就不分析了

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

#define max_number 25
int get_line(char *p[]);
void print_string(char *p[],int n);
void sort(char *p[],int n,int type);
int alpha(char *p1,char *p2);
int reverse(char *p1,char *p2);

char *p[max_number];

int get_line(char *p[])//得到字符串
{
	int n = 0;
	char buffer[80];
	puts("please a string:\n");
	while(n<25 && gets(buffer)!=0 && buffer[0]!='\0')
	{
		if ((p[n]=(char *)malloc(strlen(buffer)+1))==NULL)
			return -1;
		strcpy(p[n++],buffer);
	}
	return n;
}

void print_string(char *p[],int n)//打印字符串
{
	printf("the string is:\n");
	for (int i=0;i<n;i++)
	{
		puts(p[i]);
	}
}

void sort(char *p[],int n,int type)//排序
{
	char *temp;
	int (*compare)(char *p1,char *p2);
	compare = type ? alpha : reverse;
	for (int i=0;i<n-1;i++)
	{
		for (int j=i+1;j<n;j++)
		{
			if (compare(p[i],p[j])>0)
			{
				temp = p[i];
				p[i] = p[j];
				p[j] = temp;
			}
		}
	}
}

int alpha(char *p1,char *p2)//字典序
{
	return strcmp(p1,p2);
}

int reverse(char *p1,char *p2)//反序
{
	return strcmp(p2,p1);
}

int main()
{
	int number_of_line,type;
	number_of_line = get_line(p);
	if (number_of_line<0)
	{
		puts("memory allocation error!");
		exit(-1);
	}
	puts("before sorting:");
	print_string(p,number_of_line);
	while (1)
	{
		puts("enter 0 for reverse sort!enter 1 for alphabetical!");
		scanf("%d",&type);
 		if (((int)type!=0)&&((int)type!=1))
 		{
 			break;
 		}
 		fflush(stdin);
		sort(p,number_of_line,type);
		puts("after sorting:");
		print_string(p,number_of_line);	
	}
	system("pause");
	return 0;
}
           

感觉函数指针真心是个好玩意!!!

字符数组的排序

继续阅读