• 8. 冒泡法排序和快速排序(基于openCV)


    一、前言

    主要讲述冒泡法排序和快速排序的基本流程,并给出代码实现,亲测可用。

    二、冒泡法排序

    冒泡法排序主要是将相邻两个值比较,把小的向前冒泡,大的向后沉淀,时间复杂度为O(n2)。主要思想如下:

    分为内外循环,每次外循环确定一个大的数据的具体位置,如下实例:

    从图中可以看出,进过两次外循环就可以得到排序结果,随后的8次循环都浪费了,为了避免这种情况,我们可以设置一个状态参数,用来表示内循环是否发生数据的交换,从而作为外循环是否退出的信号。

    三、快速排序

    快速排序是最有效的排序方法之一,其主要思想是对数据进行分开排序,通过选择一个基数,然后将所要排序的数据分成两部分,一边全大,一边全小。然后利用递归的思想对分开的数据继续排序。

    四、代码实现

    冒泡法排序(输出排序后数据在原数据中的位置):

     1 void SparseGraphic::BubbleSort(const cv::Mat inMat, QVector<int> &index, cv::Mat &outMat)
     2 {
     3     if(inMat.rows!= 1)
     4         return;
     5     int col = inMat.cols;
     6     index = QVector<int>(col);
     7     for(int i = 0;i<col;i++)
     8     {
     9         index[i] = i;
    10     }
    11     if(inMat.type()!= CV_32F)
    12         inMat.convertTo(inMat,CV_32F);
    13     outMat = inMat.clone();
    14 
    15     float *ptr = outMat.ptr<float>(0);
    16     float tmpVal;
    17     int tmpIdx;
    18     for(int i = 0;i<col;i++)
    19     {
    20         for(int j = 0;j<col - i -1;j++)
    21         {
    22             if(ptr[j]>ptr[j+1])
    23             {
    24                 tmpVal = ptr[j];
    25                 ptr[j]=ptr[j+1];
    26                 ptr[j+1]=tmpVal;
    27                 tmpIdx = index[j];
    28                 index[j] = index[j+1];
    29                 index[j+1] = tmpIdx;
    30             }
    31         }
    32     }
    33 }

    快速排序(输出排序后数据在源数据中的位置):

     1 void SparseGraphic::QuickSort(cv::Mat inMat, QVector<int> &index, int low,int high)
     2 {
     3     if(inMat.rows!=1)
     4         return;
     5     float *ptr = inMat.ptr<float>(0);
     6     if(low < high)
     7     {
     8         int i = low,j = high;
     9         float X = ptr[low];
    10         while(i<j)
    11         {
    12             while(i<j && ptr[j] >= X)
    13                 j--;
    14             if(i<j)
    15             {
    16                 ptr[i++] = ptr[j];
    17                 int tmp = index[j];
    18                 index[j] = index[i-1];
    19                 index[i-1] = tmp;
    20             }
    21 
    22             while(i<j && ptr[i] < X)
    23                 i++;
    24             if(i<j)
    25             {
    26                 ptr[j--] = ptr[i];
    27                 int tmp = index[i];
    28                 index[i] = index[j+1];
    29                 index[j+1] = tmp;
    30             }
    31         }
    32         ptr[i] = X;
    33         QuickSort(inMat,index,low,i-1);
    34         QuickSort(inMat,index,i+1,high);
    35     }
    36 }
  • 相关阅读:
    第八周作业
    第八周上机练习
    第七周作业
    第七次上机练习
    第六周作业
    4.9上机作业
    第五周作业
    第四次JAVA作业
    第四周作业
    第十六次作业
  • 原文地址:https://www.cnblogs.com/zyore2013/p/4776813.html
Copyright © 2020-2023  润新知