23.冒泡排序
#include<iostream>
using namespace std;
int main()
{
int arr[] = { 1,3,4,5,3,3,5,22,4,5,6,7 };
int len = sizeof(arr) / sizeof(arr[0]);
//冒泡排序1:先把最值放在最后面
for (int i = 0; i < len-1; i++)
{
for (int j = 0; j < len - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int a = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = a;
}
}
}
for (int i = 0; i < len; i++)
{
cout << arr[i] << endl;
}
//冒泡排序2:先把最值换到最前面
int arr1[5] = { 300,350,200,400,250 };
//cout << sizeof(arr1) / sizeof(arr1[0]) - 1 << endl;
for (int i = 0; i < sizeof(arr1) / sizeof(arr1[0]) - 1; i++)
{
for (int j = i + 1; j < sizeof(arr1) / sizeof(arr1[0]); j++)
{
if (arr1[i] > arr1[j])//后面的每个值与前面的某个值比较
{
int a = arr1[i];
arr1[i] = arr1[j];
arr1[j] = a;
}
}
}
for (int i = 0; i < sizeof(arr1) / sizeof(arr1[0]); i++)
{
cout << arr1[i] << endl;
}
//冒泡排序3:先把最值换到最前面,从后往前比较
cout << "从后往前比较" << endl;
int arr2[5] = { 300,350,200,400,250 };
//cout << sizeof(arr2) / sizeof(arr2[0]) - 1 << endl;
for (int i = 0; i < sizeof(arr2) / sizeof(arr2[0]) - 1; i++)
{
for (int j = sizeof(arr2) / sizeof(arr2[0])-2; j >=i; j--)//从后往前比较
{
if (arr2[j] > arr2[j+1])
{
int a = arr2[j];
arr2[j] = arr2[j+1];
arr2[j+1] = a;
}
}
}
for (int i = 0; i < sizeof(arr2) / sizeof(arr2[0]); i++)
{
cout << arr2[i] << endl;
}
system("pause");
return 0;
}