冒泡排序的两种写法

#include <iostream>

using namespace std;

void bubble_1(int a[], int n);
void bubble_2(int a[], int n);

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

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


int main(int argc, char **argv)
{
	int number[8] = {23,43,15, 21, 53, 8, 2, 7};
	int number1[8] = {67, 76, 2,  1, 4, 91, 29, 10};
	bubble_1(number, 8);
	bubble_2(number1, 8);

	for (int i=0; i<8; i++)
	{
		cout << number[i] << " " ;
	}
	cout << " " << endl;
	for (int i=0; i<8; i++)
	{
		cout << number1[i] << " ";
	}

	return 0;
}

点赞