C++冒泡排序的几个简单实例

给数字和字符串排序

#include
using namespace std;
int main()
{
 int a[] = { 67,56,35,46,78 };//开一个int数组,存5个数字
 char b[] = "sdaferffaa";//开一个char数组,存一个字符串
 int n = 5;//n为数组a的数字个数

给数字排序

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]);
   }
  }
 }//共循环n*(n-1)/2次,从小到大排序
 //输出
 for(int i = 0;a[i]; i++)
 {
  cout << a[i];
 }

给字符排序

for (int j = 0; b[j + 1]; j++)//b[j+1]=0时,循环结束
 {
  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]))//strlen是计算数组长度的函数
   {
    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])//*s[i]=s[i][0]
   {
    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)//strcmp用于比较两个字符串,自左向右逐个字符比较ASCII值,基本形式strcmp(str1,str2),str1=str2,返回值为0,str1>str2,返回值为正数,str1
   {
    swap(s[i], s[i + 1]);
   }
  }
 }
 for (int i = 0; s[i]; i++)
 {
  cout << s[i] << endl;
 }

你可能感兴趣的:(C++冒泡排序的几个简单实例)