1. 程式人生 > 其它 >利用氣泡排序法和選擇排序法對字元排序

利用氣泡排序法和選擇排序法對字元排序

對字串中的字元進行排序所依據的是ASCII碼進行排序。

任意輸入一串字元,通過ASCII碼對其中的字元進行排序。

一、選擇排序法

//利用選擇排序法對字串中的字元進行排序
#include	<stdio.h>
#include	<string.h>
#define SIZE 80
int	main(void)
{
	char names[SIZE];
	char dates[SIZE];
	char *ptchar=NULL;
	fgets(names,SIZE,stdin);
	if (ptchar=strchr(names,'\n'))//這個if和else語句是用來優化fgets函式的。 
	{
		*ptchar='\0';	
	}
	else 
	{
		while (getchar()!='\n')
		{
			continue;
		}
	}
	for (int n=0;n<strlen(names);n++)//這裡n<SIZE也是可以的,只不過會增加任務量。
	{
		dates[n]=names[n];
	}
	int out_i;
	int in_i;
	for (out_i=0;out_i<strlen(dates)-1;out_i++)//strlen()表示一個字串不含空字元的長度,我需要比較的也正是這部分。
	{
		for (in_i=out_i+1;in_i<strlen(dates);in_i++)
		{
			if (dates[out_i]>dates[in_i])
			{
				char agent;
				agent=dates[out_i];
				dates[out_i]=dates[in_i];
				dates[in_i]=agent;
			}
		}
	}
	printf("print the original characters :%s\n",names);
	printf("print the changed characters :%s\n",dates);
	
	return	0;
} 

列印結果如下:

I love Micy very much
print the original characters :I love Micy very much
print the changed characters : IMcceehilmoruvvyy

二、氣泡排序法

//利用氣泡排序法對字串進行排序
#include	<stdio.h>
#include	<string.h>
#define SIZE 80

int	main(void)
{
	char names[SIZE];
	char dates[SIZE];
	char *ptchar=NULL;
	fgets(names,SIZE,stdin);
	if (ptchar=strchr(names,'\n'))
	{
		*ptchar='\0';
	}
	else
	{
		while (getchar()!='\n')
		{
			continue;	
		}	
	}
	for (int n=0;n<strlen(names);n++)
	{
		dates[n]=names[n];
	}
	int out_i;
	int in_i;
	for (out_i=0;out_i<strlen(dates)-1;out_i++)
	{
		for (in_i=0;in_i<strlen(dates)-1-out_i;in_i++)
		{
			if (dates[in_i]>dates[in_i+1])
			{
				char agent;
				agent=dates[in_i];
				dates[in_i]=dates[in_i+1];
				dates[in_i+1]=agent;
			}
		}
	}
	printf("print the original characters :%s\n",names);
	printf("print the changed characters :%s\n",dates);
	
	return	0;		
} 

列印結果如下:

I love Micy very much
print the original characters :I love Micy very much
print the changed characters : IMcceehilmoruvvyy