(2) Sorting algorithm: select sorting

The main points of selection sorting: find the smallest integer from the current unsorted integers, and put it at the end of the sorted list (note the two keywords: sorted and unsorted), that is, select the smallest value for sorting Put it to the left.

Contrast bubbling sorting: each comparison of bubbling sorting may be interactive , and each traversal of selective sorting only records the subscript with the smallest value of the current traversal , and only one exchange occurs after the traversal is completed.

 

Code and debugging results:

#include <iostream>

using namespace std;

void select_sort(int list[], int num)
{
	int min_pos = 0; //每次循环最小数的位置

	for (int i = 0; i < num - 1; i++)
	{
		min_pos = i;

		for (int j = i + 1; j < num; j++)
		{
			if (list[min_pos] > list[j])
				min_pos = j; //记录最小数值的下标
		}

		swap(list[i],list[min_pos]); //每次遍历只发生一次交换
	}
}


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

	select_sort(arr,sizeof(arr)/sizeof(arr[0]));

	for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++)
		cout << arr[i] << " ";

	cout << endl << endl << endl << endl;

	return 0;
}

 

Time complexity of selection sort:

    Number of comparisons: (N-1) + (N-2)+ ... + 2 + 1 = ((N-1) + 1) *(N-1)/2 = N^2/2-N/ 2;

   Number of exchanges: N-1

   Therefore, the time complexity is: (N^2/2-N/2) + (N-1) = N^2/2+N/2-1

   According to the Big O rule, the highest order term is retained, and the constant silver is taken out. The time complexity is O(N^2)

 

 

Guess you like

Origin blog.csdn.net/weixin_40204595/article/details/106311537