冒泡排序的C++实现

时间:2022-12-29 20:42:33

虽然冒泡排序是一个简单的程序,但是也可以从中去理解算法的时间复杂度和空间复杂度等概念。


#include<ctime>
#include<cstdio>
using namespace std;
const int ArrSize = 100;
void BubbleSort(int * arr, int length);
void Show(int * arr, int length);
void Swap(int & i, int & j);
int main()
{
srand(time(0));
int arr[ArrSize] = { 0 };
int i = 0;
while (i < ArrSize)
arr[i++] = rand();
arr[9] = -959;
Show(arr, ArrSize);
BubbleSort(arr, ArrSize);
Show(arr, ArrSize);
return 0;
}

void BubbleSort(int * arr, int length)
{
if (length <= 1)return;
for (int i = 0; i < length; ++i)
{
for (int j = i + 1; j < length;++j)
if (arr[j] < arr[i]) Swap(arr[i], arr[j]);//如果arr[i]后面的某一个元素比其小,交换两个的数据
} //依次完成后保证arr[i]右边的数据都比它大
}
void Swap(int & i, int & j)
{
int temp = i;
i = j;
j = temp;
}
void Show(int * arr, int length)
{
if (length <= 0)return;
cout << "The array is :\n";
for (int i = 0; i < length; ++i)
cout << arr[i] << "\t";
cout << endl;
}
Show(arr, ArrSize);

BubbleSort(arr, ArrSize);
Show(arr, ArrSize);
return 0;
}
void BubbleSort(int * arr, int length)
{
if (length <= 1)return;
for (int i = 0; i < length; ++i)
{
for (int j = i + 1; j < length;++j)
if (arr[j] < arr[i]) Swap(arr[i], arr[j]);//如果arr[i]后面的某一个元素比其小,交换两个的数据
} //依次完成后保证arr[i]右边的数据都比它大
}
void Swap(int & i, int & j)
{
int temp = i;
i = j;
j = temp;
}
void Show(int * arr, int length)
{
if (length <= 0)return;
cout << "The array is :\n";
for (int i = 0; i < length; ++i)
cout << arr[i] << "\t";
cout << endl;
}

void BubbleSort(int * arr, int length)
{
if (length <= 1)return;
for (int i = 0; i < length; ++i)
{
for (int j = i + 1; j < length;++j)
if (arr[j] < arr[i]) Swap(arr[i], arr[j]);//如果arr[i]后面的某一个元素比其小,交换两个的数据
}//依次完成后保证arr[i]右边的数据都比它大
}
void Swap(int & i, int & j)
{
int temp = i;
i = j;
j = temp;
}
void Show(int * arr, int length)
{
if (length <= 0)return;
cout << "The array is :\n";
for (int i = 0; i < length; ++i)
cout << arr[i] << "\t";
cout << endl;
}

#include<iostream>