jacky860226
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    1
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- slideOptions: transition: slide --- <!-- .slide: data-transition="fade-in convex-out" --> # ```std::sort```<br>&<br>```next_permutation``` 南天門日月卦長 --- <!-- .slide: data-transition="fade-in convex-out" --> ## 課前小提醒 * 今天要教的東西都會在```<algorithm>```標頭檔裡喔<br>記得```#include<algorithm>```! * algorithm的中文翻譯就是演算法的意思 * 裡面有很多別人幫你寫好的演算法```template<>``` * [cplusplus Reference algorithm](http://www.cplusplus.com/reference/algorithm/) --- <!-- .slide: data-transition="fade-in convex-out" --> ## ```std::sort``` --- ## 排序好慢 還記得我們之前教的排序sort嗎? 複雜度都是$\mathcal O(N^2)$ 但是排序目前被證明最快可以做到$\mathcal O(N log N)$ ---- ## STL可以排序嗎? 而且我們教的排序只能用在陣列上 那STL的<br>vector、stack、queue、deque、list可以排序嗎? ---- ## STL sort * 幸好C++ STL的開發者解決了這個問題 * 在```<algorithm>```裡面一些專門用來排序的函數 * 讓我們一起來看看這些函數吧! --- ## ```std::sort()``` * 複雜度$\mathcal O(N log N)$ * 用template實作,不用擔心型態問題 * 使用[Introsort(introspective sort)](https://en.wikipedia.org/wiki/Introsort) * 可以使用在一般的陣列<br>或是有Random Access Iterator的STL容器 ---- ## Random Access Iterator? 初學者可以理解成: 有Random Access Iterator的STL容器 都有類似陣列的功能 * 以下為目前教過有Random Access Iterator的容器 * std::vector * std::deque ---- ## sort使用方法(STL容器) ```sort(起始iterator, 結尾iterator);``` ```cpp= std::vector<int> s; for(int i=0;i<10;++i){ s.push_back(rand());//隨機產生元素 } std::sort(s.begin(), s.end());//由小排到大 for(int e:s) std::cout << e << '\n'; ``` ---- ## sort使用方法(一般陣列) 可以把iterator想成指標 ```sort(陣列起始位置, 陣列結束位置);``` ```cpp= int s[10]; for(int i=0;i<10;++i) s[i] = rand(); std::sort(s, s+10);//由小排到大 for(int e:s) std::cout << e << '\n'; ``` --- ## compare function 1 比較函數 ---- ## 由大排到小? 直接呼叫sort他會幫你把東西由小排到大 那如果要由大排到寫怎麼辦呢? 難道在sort完之後再用for把陣列顛倒? ---- ## 隱藏的東西 * std::sort其實有第三個隱藏的參數 * 這個參數要填的是一個特定型態的函數! ```cpp= bool cmp(int a,int b){ return a > b; } int main(){ vector<int> s = {7, 1, 2, 2, 9, 4, 8, 7}; sort(s.begin(), s.end(), cmp); for(int e:s) cout<<e<<endl; return 0; } ``` ---- ## 解析 * 以由大排到小為例,Type是要排序的元素型態 * 函數會回傳一個bool值: * true: ```if(a!=b)```排序後a會排在b的前面 * false: ```if(a!=b)```排序後b會排在a的前面 ```cpp= bool function_name(Type a,Type b){ return a > b; } ``` --- ## compare function 2 struct/class 也可以拿去排序喔! ---- ## struct排序 * 給你一個struct的陣列 * 你要先依照id由小到大排序 * 如果有id相同的部分就按造val由大到小排序 ``` cpp= struct GG{ int id, val; }; vector<GG> s; ``` ---- ## 比較函數 * 原則和一般的比較函數一樣: * true: ```if(a!=b)```排序後a會排在b的前面 * false: ```if(a!=b)```排序後b會排在a的前面 ```cpp= bool cmp(const GG &a, const GG &b){ if(a.id!=b.id) return a.id < b.id; return a.val > b.val; } ``` ---- ## 更精簡的寫法 這樣寫更短且函數執行解果不會改變 ```cpp= bool cmp(const GG &a, const GG &b){ return a.id<b.id||(a.id==b.id&&a.val>b.val); } ``` --- <!-- .slide: data-transition="fade-in convex-out" --> ## std::stable_sort --- ## 穩定排序 * 如果陣列中有兩個相同的元素 * 排序的時候他們的相對位置不會改變的排序 * 就稱為穩定排序 * 剛剛教的std::sort **「不是」** 穩定排序 ---- ## std::stable_sort * STL也有內建穩定排序 * 使用[merge sort](https://en.wikipedia.org/wiki/Merge_sort) * 用法和std::sort一樣 * 也可以使用比較函數 * 以下附上幾個範例給大家參考 ---- ## 一般陣列 ```cpp= int s[]={7,1,2,2,8,9,5,6}; stable_sort(s, s+8); ``` ---- ## STL 容器 ```cpp= vector<int> s={7,1,2,2,8,9,5,6}; stable_sort(s.begin(), s.end()); ``` ---- ## 比較函數 ```cpp= struct P{ int id, val; P(int id, int val):id(id), val(val){} } bool cmp(const P &a, const P &b){ return a.id<b.id||(a.id==b.id&&a.val>b.val); } vector<P> s; int main(){ for(int i=0;i<5;++i){ int id=rand(); s.puah_back(P(id,rand())); s.puah_back(P(id,rand())); } stable_sort(s.begin(), s.end(), cmp); } ``` --- <!-- .slide: data-transition="fade-in convex-out" --> ## next_permutation 中文直接翻譯就是下一個排列 --- ## 所有排列 * 高中數學學過,$N$個東西可以有$N!$種排列 * 將所有排列按造字典順序印出來 * 你會發現第一個排列是由小排到大<br>最後一個排列是由大排到小 ---- ## 範例 * {1,2,3}的所有排列(依字典順序排): 1. {1, 2, 3} 2. {1, 3, 2} 3. {2, 1, 3} 4. {2, 3, 1} 5. {3, 1, 2} 6. {3, 2, 1} ---- ## 下一個排列 * 我們說某個排列$P$的下一個排列 * 指的是將所有排列依字典順序排之後 * 編號為$P$的編號+1的那個排列 * 例如{1, 3, 2}的下一個排列就是{2, 1, 3} --- ## 產生下一個排列 * [Next lexicographical permutation algorithm](https://www.nayuki.io/page/next-lexicographical-permutation-algorithm) * C++ STL已經幫你寫好了,只要會用就行了 ---- ## std::next_permutation * 傳入的參數和sort一樣 * 他會還傳一個bool<br>如果是true表示現在這個排列不是最後一個排列 ```cpp= int s[] = {1, 3, 2}; bool end = next_permutation(s, s+3); cout<<end<<'\n'; for(int i=0;i<3;++i) cout<<s[i]<<' '; ``` ---- ## STL 容器也可以用 ```cpp= vector<int> s = {1, 3, 2}; bool end = next_permutation(s.begin(), s.end()); cout<<end<<'\n'; for(int i=0;i<3;++i) cout<<s[i]<<' '; ``` ---- ## 產生所有排列 * 只要給出第一個排列 * 不斷呼叫next_permutation * 直到回傳值變成false就行了 ```cpp= int s[]={1,2,3}; do{ for(int i=0;i<3;++i){ if(i) cout<<' '; cout<<s[i]; } cout<<'\n'; }while(next_permutation(s, s+3)); ``` ---- ## 比較函數 next_permutation也可以用比較函數喔! 程式碼已經重複出現很多次了我就不放了 --- ## 題目練習 [文字轉轉轉](https://neoj.sprout.tw/problem/153/)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully