冒泡法和选择法 排序算法实现

@冒泡法和选择法 排序算法实现

void swap(int& a, int& b)
{
	int temp=0;
	
	temp = a;
	a = b;
	b = temp;
}

void bubble_sort(int a[], int n)
{
	int i,j;
	int temp;
	int flag = 1;//设置标志,如果第一次循环比较时没有发生交换,则说明数组是升序排序,不用排序,提前结束循环
	
	for(i=0; (i<n-1)&&(flag == 1); i++)
	{
		flag = 0;
		for(j=0; j<n-i-1; j++)
		{
			if(a[j] < a[j+1])
			{
				swap(a[j], a[j+1]);
				flag = 1;
			}
		}
	}
}

void select_sort(int a[], int n)
{
	int i, j;
	
	for(i=0; i<n-1; i++)
	{
		for(j=i+1; j <n; j++)
		{
			if(a[j] < a[i])
			{
				swap(a[i], a[j]);
			}
		}
	}
}

void select_sortwithflag(int a[], int n)
{
	int i, j, k;
	
	for(i=0; i<n-1; i++)
	{
		k = i;
		for(j=i+1; j <n; j++)
		{
			if(a[j] > a[k])
			{
				k = j;
			}
		}
		
		if(i != k)
		{
			swap(a[i], a[k]);
		}
	}
}

int main()
{
	int i = 0;
	int a[10]={100,102, 104,99, 88, 98, 110, 103,1,69};
	int b[10]={100,102, 104,99, 88, 98, 110, 103,1,69};
	
	printf("The bubble sort arithmetic:\r\n");
	printf("Before sort the data is :");
	for(i=0; i<10; i++)
	{
		printf(" %d ", a[i]);
	}
	printf("\r\n");
	bubble_sort(a, 10);
	printf("After sort the Data is : ");
	for(i=0; i<10; i++)
	{
		printf(" %d ", a[i]);
	}
	printf("\r\n");
	
	printf("The selection sort arithmetic:\r\n");
	printf("Before sort the data is :");
	for(i=0; i<10; i++)
	{
		printf(" %d ", b[i]);
	}
	printf("\r\n");
	select_sort(b, 10);
	printf("After sort the Data is : ");
	for(i=0; i<10; i++)
	{
		printf(" %d ", b[i]);
	}
	printf("\r\n");
}

The output of validation.

[tcsh] hanwuwex@bjsxfrax001:/local/hanwuwex/work> ./demo
The bubble sort arithmetic:
Before sort the data is : 100  102  104  99  88  98  110  103  1  69
After sort the Data is :  110  104  103  102  100  99  98  88  69  1
The selection sort arithmetic:
Before sort the data is : 100  102  104  99  88  98  110  103  1  69
After sort the Data is :  1  69  88  98  99  100  102  103  104  110
[Linux]                                                                         [tcsh] hanwuwex@bjsxfrax001:/local/hanwuwex/work>
    原文作者:排序算法
    原文地址: https://blog.csdn.net/u014100559/article/details/82970278
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞