实测冒泡排序、简单选择排序、直接插入排序的性能

分别使用1e3、1e4、1e5大小的随机数组测试性能。直接插入的性能最好

  冒泡 简单选择 直接插入
1e3 2 ms 1 ms 0 ms
1e4 224 ms 37 ms 15 ms
1e5 25708 ms 3709 ms 1468 ms

测试代码如下:

#include<vector>
#include<cstdlib> 
#include<ctime>
using namespace std;

void testPerformance(void(*sortFun)(vector<int>&),int);
void bubbleSort(vector<int>&);
void simpleSlectionSort(vector<int>&);
void straightInsertionSort(vector<int>&);

const int N = 1e3;
int main() 
{
	cout << "bubbleSort:" << endl;
	testPerformance(bubbleSort, N);
	cout << endl;


	cout << "simpleSlectionSort:" << endl;
	testPerformance(simpleSlectionSort, N);
	cout << endl;

	cout << "straightInsertionSort:" << endl;
	testPerformance(straightInsertionSort, N);
	cout << endl;

}

void straightInsertionSort(vector<int> &a) 
{
	int len = a.size();
	for (int i = 0; i < len - 1; i++) 
	{
		int j = i;  // 向前滑动寻找插入位置
		int tmp = a[i + 1];
		while (j>=0 && tmp<a[j])
		{
			a[j + 1] = a[j];
			j--;
		} // 将i+1插入到j+1
		a[j + 1] = tmp;
	}
}

void simpleSlectionSort(vector<int> &a) 
{
	int len = a.size();
	for (int i = 0; i < len-1; i++) 
	{
		int argmin = i;
		for (int j = i + 1; j < len; j++) 
		{
			if (a[j] < a[argmin]) 
			{
				argmin = j;
			}
		}
		swap(a[i], a[argmin]);
	}
}

void bubbleSort(vector<int> &a)
{
	int len = a.size();
	for (int i = 0; i < len - 1; i++)
	{
		for (int j = len - 1; j > 0; j--)
		{
			if (a[j] < a[j - 1])
			{
				swap(a[j], a[j - 1]);
			}
		}
	}
}

void testPerformance(void(*sortFun)(vector<int>&),int n) 
{
	srand(0);
	vector<int>a(n);
	for (int i = 0; i < n; i++)
	{
		a[i] = rand();
	}
	clock_t time_start = clock();
	sortFun(a);
	clock_t time_end = clock();
	cout << "time use:" << 1000 * (time_end - time_start) / (double)CLOCKS_PER_SEC << "ms" << endl;
}
发布了7 篇原创文章 · 获赞 3 · 访问量 6143

猜你喜欢

转载自blog.csdn.net/wuweikai0617/article/details/104802846
今日推荐