选择排序
学生成绩降序排列。
#include<iostream>
using namespace std;
int main()
{
const int scores = 5;
int n, a[scores], i, j;
for (n = 0; n < scores; n++)
{
cin >> a[n];
if (a[n] < 0)
break;
}
for (i = 0; i < n - 1; i++)
{
for (j = i + 1; j < n; j++)
{
if (a[i] < a[j])
{
int t;
t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
for (i = 0; i < n; i++)
{
cout << a[i] << "\t";
}
return 0;
}
冒泡排序
#include<iostream>
using namespace std;
void bubblesort(int *arr,int len)
{
for (int i = 0; i < len - 1; i++)
{
for (int j = 0; j < len - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main()
{
int arr[] = { 4,3,5,2,1 };
cout << "排序前的数组:";
for (int i = 0; i < 5; i++)
{
cout << arr[i] << " ";
}
cout << endl;
int len = sizeof(arr) / sizeof(arr[0]);
bubblesort(arr, len);
cout << "排序后的数组:";
for (int i = 0; i < 5; i++)
{
cout << arr[i]<<" ";
}
}