常用算法

在进行编程之前,首先想想一个算法怎么能快速验证它的正确性呢,通过数学逻辑推理的确是一种不错的方法,不过在考试时间,等你证明完黄花菜估计都凉了。看左神视频,了解到一种验证方法,步骤如下:(一)设计一个随机数发生器,(数组长度随机,内容随机)(二)写入一个绝对正确的方法。(你自己写的算法可能因为时间复杂度等原因过不了测试

C++对数发生器代码:https://blog.csdn.net/opooc/article/details/80939012

模板:避免因为重载函数不全面而引起的调用错误。

对数发生器里面用到了模板的概念:http://www.kuqin.com/language/20090405/44193.html

基本算法摘抄:http://www.cnblogs.com/eniac12/p/5329396.html

(一)冒泡排序法。

notice:关于while(cin)的用法:https://blog.csdn.net/u010183589/article/details/50466465

(二)选择排序法。

(三)插入排序法。

using namespace std;

void swap(int A[],int i,int j){
      int temp = A[i];
      A[i] = A[j];
      A[j] =temp;
}
void BubbleSort(int A[],int n){//冒泡排序
    for(int i =0;i<n-1;i++){
      for(int j=0;j<n-i-1;j++)
      {
            if(A[j]>A[j+1])
          {
              swap(A,j,j+1);
          }
      }
    }
}
void SelectSort(int A[],int n){//选择排序
    for(int i=0;i<n-1;i++){
       int min = i;
       for(int j=i+1;j<n;j++){
           if(A[min]>A[j]){
              min = j;  
           }  
       }
        swap(A,min,i);
    }
}
void InsertSort(int A[],int n){ //插入排序       
    for(int i=1;i<n;i++){
        for(int j=i-1;j>=0;j--){
            if(A[j]>A[j+1]){
                swap(A,j,j+1);
            }                               
        }
    }
}
int main(){
    int a[] ={5,8,6,2,4,3,7,9};
    int n = sizeof(a)/sizeof(int);
    InsertSort(a,n);
    for(int i=0;i<n;i++){
        cout<<a[i];
    }
    system("pause");
}    

posted on 2018-10-04 17:01  萧萧小136  阅读(134)  评论(0编辑  收藏  举报

导航