C++冒泡排序实现数组排序
C++冒泡排序基本语法(用int型做例子):
int arr[9] = { 2,4,124,43,525,24,34,5,24 };
for (int i = 0; i < 9 - 1; i++)
{
for (int j = 0; j < 9 - 1 - i; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
下面是实际例子(也是用int型为例):
#include<iostream>
using namespace std;
#include<string>
void mysort(int* p)
{
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9 - i - 1; j++)
{
if (p[j] > p[j + 1])
{
int temp = p[j + 1];
p[j + 1] = p[j];
p[j] = temp;
}
}
}
}
int main()
{
int arr[10] = {};
cout << "请输入10个数字" << endl;
for (int i = 0; i < 9; i++)
{
cin >> arr[i];
}
mysort(arr);
cout << "排列后的数组" << endl;
for (int i = 0; i < 9; i++)
{
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
|