二分查找
1.输入的为一个有序的元素列表(必须有序)
2.查找的元素包含在列表中,二分查找返回位置,否则返回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;
}
大O表示法
是一种特殊的表示法,指出了算法的速度有多快
指的并非以秒为单位的速度
选择排序
直接选择排序(Selection Sort),这是一种简单直观的排序算法。它首先在未排序序列中找到最小(大)元素,存放到排序序列的其起始位置,然后再从剩余未排序的序列元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素排序完毕。
如图所示的操作方式
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;
}