# include<iostream>
using namespace std;
int main()
{
int a[11] = { 0 }, i, j, t;
for (i = 1; i <= 5; i++)
{
cin>>t;
a[t]++;
}
for (i = 0; i <= 10; i++)//可以根据从大到小或从小到大的顺序改写起始表达式跟条件表达式
{
for (j = 1; j<=a[i]; j++)
{
cout<<i;
}
}
system("pause");
return 0;
}
冒泡排序
基本思想是:每次比较两个相邻的元素,如果他们的顺序错误就把他们交换过来。
# include<iostream>
using namespace std;
int main()
{
int a[100];
int i, j, t, n;
cin >> n;
for (i = 1; i <= n; i++)
{
cin >> a[i];
}
for (i = 1; i <= n - 1; i++)
{
for (j = 1; j <= n - i; j++)
{
if (a[j] > a[j + 1])
{
t = a[j]; a[j] = a[j + 1]; a[j + 1] = t;
}
}
}
for (i = 1; i <= n; i++)
{
cout << a[i] << " ";
}
system("pause");
return 0;
}
接下来这个算法利用冒泡的特性解决了桶排序得字符问题
# include<iostream>
using namespace std;
struct student
{
char name[20];
int score;
};
int main()
{
struct student a[100];
int i, j, n,t;
cin >> n;
for (i = 1; i <= n; i++)
{
cin >> a[i].name;
cin >> a[i].score;
}
for (i = 1; i <= n - 1; i++)
{
for (j = 1; j <= n - i; j++)
{
if (a[j].score > a[j + 1].score)
{
t = a[j].score; a[j].score = a[j + 1].score; a[j + 1].score = t;
}
}
}
for (i = 1; i <= n; i++)
{
cout << a[i].name << a[i].score << endl;
}
system("pause");
return 0;
}
快速排序
# include<iostream>
using namespace std;
int a[101], n;
void quicksort(int left, int right)
{
int i, j, t, temp;
if (left > right)
{
return;
}
temp = a[left];
i = left;
j = right;
while (i != j)
{
while (a[j] >= temp && i < j)
{
j--;
}
while (a[i] <= temp && i < j)
{
i++;
}
if (i < j)
{
t = a[i]; a[i] = a[j]; a[j] = t;
}
}
a[left] = a[i];
a[i] = temp;
quicksort(left, i - 1);
quicksort(i + i, right);
}
int main()
{
int i, j, t;
cin >> n;
for (i = 1; i <= n; i++)
{
cin >> a[i];
}
quicksort(1, n);
for (i = 1; i <= n; i++)
{
cout << a[i] << " ";
}
system("pause");
return 0;
}