冒泡排序---带过程分析

冒泡排序

两层for循环,只需要记住初始条件和升序/降序规则即可。

#include <stdio.h>
#include <iostream>
using namespace std;
class solution {
public:
  solution(){}
  void sort(int *src, int srcNum){
      for (int i = 0; i < srcNum; i++){
          cout<<"第"<<i+1<<"轮排序过程:"<<endl;
          for (int j = i+1; j < srcNum; j++){
              cout<<"j="<<j<<":";
              if (src[i]>src[j]){//升序--降序
                  int temp = src[i];
                  src[i] = src [j];
                  src[j] = temp;
              }
                PrintSrc(src, srcNum);
          }
      }
  }
  void PrintSrc(int *src, int srcNum) {
      for (int i = 0; i < srcNum; i++) {
          cout<<src[i]<<' ';
      }
      cout<<endl;
  }
};
int main()
{
  int src[5] ={5,4,3,2,1};
  solution *obj = new solution();
  cout<<"排序前:"<<endl;
  obj->PrintSrc(src,sizeof(src)/sizeof(src[0]));
  obj->sort(src,sizeof(src)/sizeof(src[0]));
  cout<<"排序后:"<<endl;
  obj->PrintSrc(src,sizeof(src)/sizeof(src[0]));
  if (obj != nullptr) {
      delete obj;
      obj = nullptr;
  }
  return 0;
}

你可能感兴趣的:(C++学习心得)