快速排序算法:其中T为测试次数,n为元素个数
#include <iostream>
using namespace std;
int partition(int *s, int low, int high)
{
int i, j, t;
int pivot = s[low];
j = low;
for (i = low + 1; i <= high; i++)
{
if (s[i] < pivot)
{
j++;
t = s[i];
s[i] = s[j];
s[j] = t;
}
}
t = s[j]; //交换pivot和比pivot小的序列的最后一个数
s[j] = pivot;
s[low] = t;
return j;
}
void Quicksort(int *s, int low, int high)
{
int pivot; //中枢轴
if (low < high)
{
pivot = partition(s, low, high);
Quicksort(s, low, pivot - 1); //对低子表递归排序
Quicksort(s, pivot + 1, high); //对高子表递归排序
}
}
int main()
{
int T, N;
int i;
int a[1000];
cin >> T;
while (T--)
{
cin >> N;
for (i = 0; i < N; i++)
cin >> a[i];
Quicksort(a, 0, N - 1);
for (i = 0; i < N; i++)
cout << a[i] << endl;
}
return 0;
}
冒泡排序算法:其中T为测试次数,n为元素个数
#include <iostream>
using namespace std;
int main()
{
int T, N;
int i, j, k, t;
int a[1000];
cin >> T;
while (T--)
{
cin >> N;
for (i = 0; i < N; i++)
cin >> a[i];
for (j = 0; j < N - 1; j++)
{
for (k = 0; k < N - j - 1; k++)
{
if (a[k] > a[k + 1])
{
t = a[k + 1];
a[k + 1] = a[k];
a[k] = t;
}
}
}
for (i = 0; i < N; i++)
cout << a[i] << endl;
}
return 0;
}