冒泡算法实现

冒泡算法的思想是依次两两比较待排序的数组元素;若为逆序(递增或递减)则进行交换,将待排序元素从左至右比较一遍称为一趟"冒泡"。每趟冒泡都将待排序列中的最大关键字交换到最后(或最前)的位置,直至所有元素有序为止。

#include <iostream>

using namespace std;

void MaopaoSort(int *array, int count);
void printArray(int *array, int count);
void swap(int x, int y);

int main()
{
	int count;
	
	cout << "请输入数组长度: ";
	cin >> count;

	while(isdigit(count))
	{	
		cout << "请输入整数: ";
		cin >> count;
	}
	
	int *array = new int[count]; 
	cout << "请输入长度为 " << count << " 数组: ";
	for(int i=0; i<count; i++)
	{
		cin >> array[i];
		cout << "第" << i << "个数: " << array[i] << endl;
	}

	cout << "Before sort: " << endl;
	printArray(array, count);
	cout << endl;
	
	MaopaoSort(array, count);

	cout << "After sort: " << endl;
	printArray(array, count);
	cout << endl;

	return 0;
}

void swap(int *x, int *y)  //用异或的方法交换两个数
{
	*x ^= *y;
	*y ^= *x;
	*x ^= *y;
}

void MaopaoSort(int *array, int count)   //冒泡算法
{
	//int iTemp;

	for(int i=1; i<count; i++)
	{
		for(int j=count-1; j>=i; j--)
		{
			if(*(array+j) < *(array+j-1))
			{
				/*
				iTemp = *(array+j-1);
				*(array+j-1) = *(array+j);
				*(array+j) = iTemp;
				*/

				swap(array+j-1, array+j);
			}
		}
	}
}

void printArray(int *array, int count)   //打印数组
{
	for(int i=0; i<count; i++)
	{
		cout << *(array+i) << "\t";
	}
}

要点:

1、采用异或的方法交换两个数

2、判断输入是否为数字函数:isdigit()

3、判断一个数字是否是整数:n==int(n)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值