排序與二分搜

排序

把東西排好

怎麼排?

常見比較慢的排序演算法

泡沫排序(bubble sort)

選擇排序(selection sort)

插入排序(insertion sort)

以上最壞複雜度皆為O(n^2)

裸題

#include<iostream>
using namespace std;
int power(int x, int n) {
    if (n == 1) {
        return x;
    }
    if (n & 1) {
        return power(x, n - 1) * x;
    }
    else {
        int tmp = power(x, n / 2);
        return tmp * tmp;
    }
}
int main()
{
    int x, n;
    cin >> x >> n;
    cout << power(x, n) << '\n';
    return 0;
}

<algorithm>

內建的sort函式

sort(iter first, iter last)

sort(iter first, iter last, Cmp cmp)

看不懂?

範例code

#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(int a,int b){
	return a>b;
}
int main(){
	int a[5]={3,2,5,1,4};
	sort(a,a+5);
	for(int i=0;i<5;i++)
		cout<<a[i]<<' ';//1 2 3 4 5
	cout<<'\n';
	sort(a,a+5,cmp);
	for(int i=0;i<5;i++)
		cout<<a[i]<<' ';//5 4 3 2 1
}

裸題

排序

排序完了 然後可以幹嘛?

二分搜!

搜尋

一個一個找

O(n)

二分搜

要排序好

O(\log n)

code

#include<iostream>
#include<algorithm>
using namespace std;
int a[5]={10,-3,5,2,7};
bool f(int l,int r,int v){
	//[l,r)
	if(l+1==r) return a[l]==v;
	int m=(l+r)/2;
	if(a[m]>v) return f(l,m,v);
	if(a[m]==v) return true;
	return f(m,r,v);
}
int main(){
	sort(a,a+5);//-3 2 5 7 10
	cout<<f(0,5,5)<<'\n';//1
	cout<<f(0,5,4)<<'\n';//0
	cout<<f(0,4,10)<<'\n';//0
}
Made with Slides.com