给数字和字符串排序
#include<iostream>
using namespace std;
int main()
{
int a[] = { 67,56,35,46,78 };
char b[] = "sdaferffaa";
int n = 5;
给数字排序
for (int j = 0; j<n-1; j++)
{
for (int i = 0; i<n-1-j; i++)
{
if (a[i] > a[i + 1])
{
swap(a[i], a[i + 1]);
}
}
}
for(int i = 0;a[i]; i++)
{
cout << a[i];
}
给字符排序
for (int j = 0; b[j + 1]; j++)
{
for (int i = 0; b[i + 1 + j]; i++)
{
if (b[i] > b[i + 1])
{
swap(b[i], b[i + 1]);
}
}
}
for (int i = 0; b[i]; i++)
{
cout << b[i];
给数组排序
char s1[] = "fffa";
char s2[] = "sdaa";
char s3[] = "acb";
char s4[] = "fa";
char* s[4];
s[0] = s1;
s[1] = s2;
s[2] = s3;
s[3] = s4;
int m = 4;
按长度排序
for (int j = 0; j < m - 1; j++)
{
for (int i = 0; i < m - 1 - j; i++)
{
if (strlen(s[i]) > strlen(s[i + 1]))
{
swap(s[i], s[i + 1]);
}
}
}
for (int i = 0; s[i]; i++)
{
cout << s[i] << endl;
}
按首字母排序
for (int j = 0; j < m - 1; j++)
{
for (int i = 0; i < m - 1 - j; i++)
{
if (*s[i] > * s[i + 1])
{
swap(s[i], s[i + 1]);
}
}
}
for (int i = 0; s[i]; i++)
cout << s[i] << endl;
按字典序排序
for (int j = 0; j < m - 1; j++)
{
for (int i = 0; i < m - 1 - j; i++)
{
if (strcmp(s[i], s[i + 1]) > 0)
{
swap(s[i], s[i + 1]);
}
}
}
for (int i = 0; s[i]; i++)
{
cout << s[i] << endl;
}