`
CreazyApple
  • 浏览: 61870 次
  • 性别: Icon_minigender_1
  • 来自: 成都
文章分类
社区版块
存档分类
最新评论

冒泡排序和选择排序

 
阅读更多
/* 冒泡排序 */
#include<stdio.h>

void BubbleSort (int s[],int n)
{
	int i,j,temp=0;
	int exchange;
	exchange=0;   

	for(i=0;i<n;i++)
	{
		for(j=n-1; j > i; j--)
		{
			if(s[j] < s[j-1]){
				temp=s[j];//注意冒泡排序交换的是相邻两个元素
				s[j]=s[j-1];
				s[j-1]=temp;
				exchange=1;
			}
		}
		if(!exchange)
			return;
	}
}
/* 选择排序 */
void SelectSort(int array[], int n)
{
	int i,j,t;
	for (i=0;i<n-1;i++)
	{
		int pos = i; 
		for (j=i+1;j<n;j++)
		{
			if (array[j]<array[pos])
			{
				pos = j;//只是找到位置,并不需要每次都换一下
			}
		}
		//找到位置后才交换,不是交换相邻元素,而是把最小的元素放在s[j]中
		t = array[i];
		array[i] = array[pos];
		array[pos] = t;
	}
}
int main()
{
	int s[10] = {9,2,8,3,4,1,6,7,5,0};
	int n=10;
	int i;

	SelectSort(s,n);

	for(i=0;i<10;i++)
	{
		printf("%d ",s[i]);
	}

	getchar();
	return 0;

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics