Binary search selection sort

Binary search

1. The input is an ordered list of elements (must be ordered)

2. The searched element is contained in the list, and the binary search returns the position, otherwise it returns NULL

eg:

#include <iostream>
using namespace std;
int bianrySearch(int *a, int nLength, int val)
{
	int start = 0;
	int end = nLength - 1;
	int index = -1;
	while (start <= end)
	{
		index = (start + end) / 2;
		if (a[index] == val)
		{
			return index;
		}
		else if (a[index] < val)
		{
			start = index + 1;
		}
		else
		{
			end = index - 1;
		}
	}

	return -1;
}
int main()
{
	int a[] = { 0,1,2,3,4,5 };
	for (int i = 0; i < 6; i++)
	{
		cout << a[i] << "   ";
	}
	cout << endl;
	int k = bianrySearch(a, sizeof(a) / sizeof(int), 5);
	cout << "5在的位置为:";
	cout << k << endl;
	system("pause");
	return 0;
}

Big O notation

Is a special notation that indicates how fast the algorithm is

Not referring to speed in seconds

Select sort

Direct selection sort (Selection Sort), which is a simple and intuitive sorting algorithm. It first finds the smallest (large) element in the unsorted sequence, stores it at the beginning of the sorted sequence, and then continues to find the smallest (large) element from the remaining unsorted sequence elements, and then puts it at the end of the sorted sequence . And so on, until all elements are sorted.

Operation as shown

eg:

#include <iostream>
#include <algorithm>
using namespace std;
void SelectSort(int *a, int n)
{
	for (int i = 0; i < n - 1; i++)
	{
		for (int j = i+1; j < n; j++)
		{
			if (a[j] < a[i])
			{
				swap(a[j], a[i]);
			}
		}
	}
}
int main()
{
	int a[] = { 2,1,6,9,5,7,3 };
	SelectSort(a, 7);
	for (auto &s : a)
	{
		cout << s << " ";
	}
	cout << endl;
	system("pause");
	return 0;
}

 

Guess you like

Origin blog.csdn.net/qq_31702609/article/details/81292914