选择排序 C++

选择排序的时间复杂度为o(n*n),空间复杂度为o(n)。

逻辑分析:

1 假设数组中的最小数为a[0],然后比较数组中其他数与a[0]的大小,若a[i]<a[0],则交换两者为止,如此循环下来,最小的数字就存在a[0]里面啦。

2 然后继续将a[1]中存访后面元素最小的,一直到排序完成。

是不是很简单,对,就这么简单。

#include<iostream>
#include<cstdlib>

using namespace std;

void swap(int &a, int &b)
{
	int temp = a;
	a = b;
	b = temp;
}



void selectSort(int a[],  int length)
{
	for (int j = 0; j < length; j++)
	{
		for (int i = j+1; i < length; i++)
		{
			if (a[i] <a[j])
			{
				swap(a[i], a[j]);
			}
		}
	}
	
	
	

}

int main()
{
	int a[] = { 2,1,4,5,3,8,7,9,0,6 };

	selectSort(a, 10);

	for (int i = 0; i < 10; i++)
	{
		cout << a[i] << " ";

	}
	cout << endl;
	system("pause");
	return 0;

}

猜你喜欢

转载自blog.csdn.net/summerlq/article/details/81244460