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