算法基础——选择排序

条件:数组
思想:数组第一个元素与余下的元素相比较,如果满足比较条件,两者互换,以此类推;
比较次数:N*N/2次比较,N次交换;
特点:1.运行时间与输入无关;2.数据移动是最小的;
C++实现:

const int N = 10;
void selectionSort()
{
	 int a[N];
	 srand(time(NULL));
	 for (int i = 0; i < N; ++i)
	 {
	  	a[i] = rand() % 100; // 100 以内的数
	 }
	 // 打印输出随机数组
	 cout << "选择排序前的数组:" << endl;
	 for (int i = 0; i < N; ++i)
	 {
	 	 cout << setw(3) << a[i];
	 }
	 cout << endl;
	 for (int i = 0; i < N; ++i)
	 {
		  int temp = i;
		  for (int j = i + 1; j < N; ++j)
		  {
			   if (a[temp] < a[j])
			   {
			    	temp = j;
			   }	
		  }
		  if (temp != i)
	  	  {
			   int tempArr = a[temp];
			   a[temp] = a[i];
			   a[i] = tempArr;
		  }
	 }
	 cout << "选择排序后的数组:" << endl;
	 for (int i = 0; i < N; ++i)
	 {
	  	cout << setw(3) << a[i];
	 }
	 cout << endl;
}

你可能感兴趣的:(算法基础,算法基础)