码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-09-01 21:25:29      阅读:357      评论:0      收藏:0      [点我收藏+]

标签:

一、前言

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

二、冒泡法排序

冒泡法排序主要是将相邻两个值比较,把小的向前冒泡,大的向后沉淀,时间复杂度为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 }

 

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

标签:

原文地址:http://www.cnblogs.com/zyore2013/p/4776813.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!