Vậy là chúng ta đã được học qua 2 thuật toán sắp xếp chọn và sắp xếp nổi bọt. Vẫn còn một thuật toán sắp xếp nũa chúng ta sẽ được học trong bài hôm nay đó là là thuật toán sắp xếp chèn.

Nôi dung bao gồm:

  • Ý tưởng thuật toán
  • Cài đặt thuật toán

Nội dung chính

  • 1. Ý tưởng thuật toán sắp xếp chèn
  • 2. Cài đặt thuật toán sắp xếp chèn
  • 3. Lời kết

1. Ý tưởng thuật toán sắp xếp chèn

Ý tưởng thuật toán sắp xếp chèn như sau:

Trước hết ta xem phần tử a[0] là một dãy đã có thứ tự.

Bước 1: Chèn phần tử a[1] vào dãy a[0] theo đúng vị trí sao cho dãy a[0] và a[1] được sắp xếp đúng thứ tự.

Bước 2: Chèn phần tử a[2] vào dãy a[0], a[1] sao cho dãy a[0], a[1], a[2] được sắp xếp đúng thứ tự.

Bước i: Chèn phần tử a[i] vào dãy a[o], a[1], a[2], …, a[i-1] sao cho dãy a[o], a[1], a[2], …, a[i-1], a[i] được sắp xếp đúng thứ tự

Sau N-1 bước thì kết thúc (vì mảng có N-1 phần tử).
Lưu đồ thuật toán sắp xếp chèn:

Ví dụ: Sắp xếp tăng dần dãy 5 – 1 – 3 – 4 – 6 – 8. (Phần màu xanh là phần đã sắp xếp)

Bước 1: Coi như phần tử thứ nhất là số 5 đã được sắp xếp, dãy lúc này như sau: 5 – 1 – 3 – 4 – 6 – 8.

Bước 2: Lấy phần tử thứ hai là số 1 gán vào đúng vị trí trong dãy 5, lúc này dãy như sau: 1 – 5 – 3 – 4 – 6 – 8.

Bước 3: Lấy phần tử thứ ba là số 3 gán vào đúng vị trí trong dãy 1 – 5, lúc này dãy như sau: 1 – 3 – 5 – 4 – 6 – 8.

Bước 4: Lấy phần tử thứ tư là số 4 gán vào đúng vị trí trong dãy 1 – 3 – 5, lúc này dãy như sau: 1 – 3 – 4 – 5 – 6 – 8.

Bước 5: Lấy phần tử thứ năm là số 6 gán vào đúng vị trí trong dãy 1 – 3 – 4 – 5, lúc này dãy như sau: 1 – 3 – 4 – 5 – 6 – 8.

Bước 6: Lấy phần tử thứ sáu ( phần tử cuối cùng) gán vào đúng vị trí trong dãy 1 – 3 – 4 – 5 – 6, lúc này dãy như sau: 1 – 3 – 4 – 5 – 6 – 8.

Kết thúc: kết quả đã được sắp xếp như sau: 1 – 3 – 4 – 5 – 6 – 8

2. Cài đặt thuật toán sắp xếp chèn

Chúng ta đã được học bài xây dựng hàm trong php rồi nên tôi sẽ viết bài giải dưới dạng hàm nhé.

Sắp xếp tăng dần:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
function InsertionSort($mang)  {
    // Tổng số phần tử
    $sophantu = count($mang);
 
    // Lặp qua từng phần tử của mảng để sắp xếp
    for ($i = 0; $i < $sophantu; $i++)
    {
        // Lặp từ phần tử thứ $i, ví dụ $i = 6
        // thì sẽ lặp từ phần tử số 6 trở về 0 để kiểm tra
        $loop = $i;
 
        // Lưu lại giá trị của $mang[$i] để khỏi bị mất
        $current = $mang[$i];
 
        // điều kiện dừng là $loop <= 0 (tức là hết mảng) hoặc
        // phần tử thứ $loop - 1 bé hơn phần tử thứ $i (vì đã tìm đc đúng vị trí)
        // nếu một trong 2 điều kiện đó đúng thì sẽ dừng vòng lặp
        while($loop > 0 && ($mang[$loop - 1] > $current))
        {
            // Di dời các phần tử lên 1 bậc
            $mang[$loop] = $mang[$loop - 1];
            $loop -= 1;
        }
 
        // Gán giá trị $current vào vị trí tìm được
        $mang[$loop] = $current;
    }
 
    return $m

 

Sắp xếp giảm dần:

Sắp xếp giảm dần cũng như tăng dần, chỉ khác là ta đổi dấu điều kiện lặp trong vòng lặp while.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
function InsertionSort($mang)  {
    // Tổng số phần tử
    $sophantu = count($mang);
 
    // Lặp qua từng phần tử của mảng để sắp xếp
    for ($i = 0; $i < $sophantu; $i++)
    {
        // Lặp từ phần tử thứ $i, ví dụ $i = 6
        // thì sẽ lặp từ phần tử số 6 trở về 0 để kiểm tra
        $loop = $i;
 
        // Lưu lại giá trị của $mang[$i] để khỏi bị mất
        $current = $mang[$i];
 
        // điều kiện dừng là $loop <= 0 (tức là hết mảng) hoặc
        // phần tử thứ $loop - 1 lớn hơn phần tử thứ $i (vì đã tìm đc đúng vị trí)
        // nếu một trong 2 điều kiện đó đúng thì sẽ dừng vòng lặp
        while($loop > 0 && ($mang[$loop - 1] < $current))
        {
            // Di dời các phần tử lên 1 bậc
            $mang[$loop] = $mang[$loop - 1];
            $loop -= 1;
        }
 
        // Gán giá trị $current vào vị trí tìm được
        $mang[$loop] = $current;
    }
    return $mang;

 

3. Lời kết

Có lẽ hơi rối với thuật toán sắp xếp chèn trong php này đúng không các bạn. Mình cũng không biết giải thích thế nào cho các bạn hiểu thêm nữa, các bạn cố gắng gõ lại code, ngồi hình dung dần nhé =)). Bài tiếp theo chúng ta sẽ học phương thức get và post trong php

112 BÌNH LUẬN

  1. ลูกค้าบางส่วนที่เลือกใช้บริการกับเรา

    You’re using a browser that won’t supported by Fb, so we’ve
    redirected you to definitely a simpler version to supply you with the
    very best encounter.

    รับกลยุทธ์การตลาดดิจิทัลที่ผ่านการพิสูจน์แล้ว จากทีมผู้เชี่ยวชาญของเราสู่การเพิ่มรายได้จากฝั่งออนไลน์ของคุณ

    แอดมินดูแลเพจ เว็บไซต์ และร้านค้าออนไลน์

    เยส เว็บ ดีไซน์ สตูดิโอ เป็นบริษัทที่รับออกแบบเว็บไซต์ ที่เชี่ยวชาญในการออกแบบเว็บไซต์และพัฒนาเว็บไซต์ให้กับลูกค้าที่ขอนแก่น เราคือบริษัททำเว็บไซต์หนึ่งเดียวในขอนแก่น ที่มีการออกแบบที่โดดเด่นไม่เหมือนใคร

    ด้วยประสบการณ์อย่างยาวนานในด้านการสร้างเว็บไซต์และพัฒนาเว็บไซต์ของเราเว็บไซต์ที่ตอบโจทย์และมีประสิทธิภาพในการใช้งาน

    วิธีการใช้งานสมัครเป็นฟรีแลนซ์เริ่มขายงานอย่างไรการชำระค่าจ้างรับประกันการจ้างงานบล็อกความรู้คำถามที่เจอบ่อย

    กับวิธีรับมือที่จะช่วยให้โฆษณายังคงมีประสิทธิภาพสูงสุด รักเราให้เหมือนที่เรารักคุณ ติดตามเราได้เลย!

    เราดูแลลูกค้าด้วยการให้คำปรึกษาอย่างละเอียด และเมื่อเราเข้าใจเป้าหมายและข้อกำหนดของแบรนด์นั้นๆ แล้ว เราจะสามารถสร้างแคมเปญที่มีประสิทธิภาพ ซึ่งจะช่วยให้บริษัทของคุณเติบโตไปในทิศทางที่ดีที่สุด
    ไม่ว่าจะเป็นยอดการเข้าชมที่มากขึ้น คอนเวอร์ชั่นเรทที่สูงขึ้น การจัดอันดับที่ดีขึ้น หรือรายได้ที่มีนัยสำคัญยิ่งขึ้น
    ซึ่งเราจะทำการออกแบบกลยุทธ์เพื่อให้เหมาะกับกลุ่มลูกค้าและเป้าหมายของคุณมากที่สุด

    บริการทำการตลาดออนไลน์ เพิ่มยอดขายสินค้า โดยทีมงานมืออาชีพ

    “เราคือไพรมอล เราเป็นทีมนักการตลาดดิจิทัลระดับ⁠ท็อปของไทยที่ใส่ใจลูกค้าและมุ่งสู่ผลลัพธ์ที่ดีที่สุด”

    social banking คืออะไร จะมาเปลี่ยนโลกอย่างไร

    เนื้อหาเว็บไซต์ อัพเดทเว็บไซต์ให้มีความเคลื่อนไหวอยู่เสมอ และมีการอัพเดตเนื้อหาที่น่าสนใจ และต้องเป็นไปในทิศทางเดียวกัน และเกี่ยวข้องกับ keywords ที่ต้องการ

    ในฐานะการเป็นผู้นำทางด้านออกแบบ
    เราตั้งใจและหาวิธีทำให้ธุรกิจของคุณเป็นที่รู้จักกับลูกค้าและตรงต่อความต้องการ ต่อยอดธุรกิจ ขยายช่องทางการขาย
    และสร้างการรับรู้บนโลกออนไลน์

    ยกระดับธุรกิจของคุณกับผลลัพธ์ที่น่าพอใจ

    ให้เว็บไซต์ ไต่อันดับสูงขึ้น และมีคนเข้าเยอะกว่าเดิม

    You happen to be employing a browser that won’t supported by
    Facebook, so we have redirected you to definitely a
    simpler Variation to provde the very best knowledge.

  2. Hello mates, how is the whole thing, and what you want to say on the topic of this piece of writing, in my view its genuinely
    remarkable in favor of me.

  3. hi!,I really like your writing very a lot! share we keep in touch more about your article on AOL?
    I need an expert on this area to unravel my problem. May be that’s you!

    Having a look ahead to peer you.

  4. I’m not that much of a internet reader to be honest but your blogs really nice,
    keep it up! I’ll go ahead and bookmark your site to come back
    down the road. Many thanks

  5. Hi, I think your site might be having browser compatibility issues.
    When I look at your website in Opera, it looks fine
    but when opening in Internet Explorer, it has some overlapping.
    I just wanted to give you a quick heads up! Other then that, awesome blog!

  6. Hi there to every one, for the reason that I am genuinely eager of reading this website’s post to be updated regularly.
    It includes nice material.

  7. Hey I am so delighted I found your web site, I really found you
    by error, while I was searching on Askjeeve for something else, Nonetheless I am here now and would just
    like to say thank you for a tremendous post and a all round thrilling blog (I also love the theme/design), I don’t have time to go
    through it all at the minute but I have saved it and also included your RSS
    feeds, so when I have time I will be back to
    read a lot more, Please do keep up the excellent job.

  8. Hey! I just wanted to ask if you ever have any trouble with hackers?
    My last blog (wordpress) was hacked and I ended up losing months of hard work due to no backup.
    Do you have any solutions to prevent hackers?

  9. whoah this weblog is excellent i love reading your articles.

    Keep up the good work! You understand, a lot of persons
    are looking round for this information, you can aid them greatly.

  10. Terrific article! This is the type of info that should be shared around the web.

    Shame on the search engines for not positioning
    this submit higher! Come on over and discuss with my site
    . Thank you =)

  11. Attractive component of content. I simply stumbled upon your site and
    in accession capital to claim that I acquire actually enjoyed account your weblog posts.

    Anyway I’ll be subscribing for your augment and even I success you get admission to constantly fast.

  12. Today, I went to the beach front with my children. I found a
    sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She placed the shell to her ear
    and screamed. There was a hermit crab inside and it pinched
    her ear. She never wants to go back! LoL I know this is totally off topic but I had to tell someone!

  13. Wow, marvelous blog layout! How long have you been blogging for?

    you make blogging look easy. The overall look of your site is excellent, as well as the content!

  14. You actually make it seem so easy with your presentation but I find this topic to be actually something
    which I think I would never understand. It seems too complex and very broad for me.
    I’m looking forward for your next post, I will try to get the hang of
    it!

  15. When I initially commented I appear to have clicked the -Notify me when new comments are added- checkbox and
    now each time a comment is added I receive 4 emails with the same
    comment. Perhaps there is a way you can remove me from
    that service? Thanks a lot!

  16. I was wondering if you ever considered changing the layout of your website?
    Its very well written; I love what youve got to say.
    But maybe you could a little more in the way of content so people could connect with it better.
    Youve got an awful lot of text for only having 1 or 2 images.
    Maybe you could space it out better?

  17. Hi there! This is my first visit to your blog!
    We are a collection of volunteers and starting a new project
    in a community in the same niche. Your blog provided us valuable information to work on. You have done a extraordinary job!

  18. Link exchange is nothing else but it is simply placing the other person’s weblog link on your page at appropriate place and other person will also
    do same for you.

  19. I have to thank you for the efforts you have put in writing this blog.
    I’m hoping to see the same high-grade content from you later on as well.
    In fact, your creative writing abilities has motivated
    me to get my own, personal site now 😉

  20. Thank you, I have recently been searching for information about this topic for a
    long time and yours is the greatest I have discovered so far.
    But, what in regards to the conclusion? Are you positive about the source?

  21. Hello There. I discovered your blog using msn. This is a very well written article.

    I will be sure to bookmark it and come back to learn more of your useful information. Thank you for the
    post. I’ll certainly comeback.

  22. Its like you read my mind! You appear to know so much about this,
    like you wrote the book in it or something. I think
    that you could do with some pics to drive the message home a
    bit, but other than that, this is excellent blog. A great read.
    I will certainly be back.

  23. Hey There. I discovered your weblog using msn. That is a very well written article.

    I’ll be sure to bookmark it and come back to read more of your useful info.
    Thank you for the post. I’ll certainly comeback.

  24. Hello There. I found your blog using msn. This is a
    very well written article. I will be sure to bookmark it and
    come back to read more of your useful information.
    Thanks for the post. I will definitely comeback.

  25. A person essentially help to make severely posts I would state.
    That is the first time I frequented your web page and to this point?
    I amazed with the research you made to create this particular submit
    amazing. Magnificent task!

  26. Great items from you, man. I’ve understand your stuff previous
    to and you’re simply too magnificent. I actually like what you’ve
    bought here, really like what you are saying and the way in which by which
    you say it. You’re making it entertaining and you still take
    care of to stay it wise. I can not wait to read far more from you.
    This is actually a great site.

  27. Wonderful goods from you, man. I have understand your stuff previous to and you’re
    just extremely great. I really like what you’ve
    acquired here, certainly like what you are saying and the way in which you say it.

    You make it enjoyable and you still take care of to
    keep it wise. I can not wait to read much more from you.
    This is really a wonderful web site.

  28. It is perfect time to make a few plans for the future
    and it is time to be happy. I’ve learn this publish and if I may I want
    to counsel you few interesting things or tips. Perhaps
    you could write subsequent articles regarding this article.
    I wish to read even more issues about it!

  29. Just want to say your article is as astounding. The clearness in your post is simply nice and i can assume you are
    an expert on this subject. Fine with your permission allow me to grab
    your feed to keep updated with forthcoming post.
    Thanks a million and please continue the rewarding work.

  30. We are a group of volunteers and starting
    a new scheme in our community. Your site provided us with valuable info to work on. You have performed a formidable activity and our entire neighborhood shall be grateful to you.

  31. I get pleasure from, result in I discovered just what I
    used to be looking for. You’ve ended my four day
    lengthy hunt! God Bless you man. Have a nice day.
    Bye

  32. Howdy would you mind sharing which blog platform you’re working with?
    I’m planning to start my own blog soon but I’m
    having a tough time selecting between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your design and style seems different
    then most blogs and I’m looking for something unique.
    P.S Sorry for getting off-topic but I had to ask!

  33. Hey! Quick question that’s totally off topic.
    Do you know how to make your site mobile friendly?
    My web site looks weird when browsing from my iphone 4.
    I’m trying to find a template or plugin that might be able to resolve this problem.
    If you have any recommendations, please share. Thank you!

  34. Great blog here! Also your website loads up very fast!

    What host are you using? Can I get your affiliate link to your host?

    I wish my web site loaded up as quickly as yours lol

  35. I think this is among the most significant information for me.
    And i am glad reading your article. But want to remark on some general things, The web site style is perfect, the articles is really excellent :
    D. Good job, cheers

  36. Unquestionably believe that which you said. Your favorite
    reason appeared to be on the web the easiest thing to be
    aware of. I say to you, I certainly get irked while people consider worries
    that they plainly don’t know about. You managed to hit the nail
    upon the top and also defined out the whole thing without having side effect , people could take a signal.

    Will likely be back to get more. Thanks

  37. Hello, Neat post. There’s an issue along with your web site
    in internet explorer, might test this? IE nonetheless is the market leader and a huge section of other people will miss your magnificent writing because of this problem.

  38. Hey! Quick question that’s completely off topic.

    Do you know how to make your site mobile friendly?
    My site looks weird when browsing from my iphone4.
    I’m trying to find a theme or plugin that might be able to
    fix this problem. If you have any recommendations, please share.
    Appreciate it!

  39. you are really a just right webmaster. The web site loading velocity is incredible.
    It seems that you are doing any distinctive trick.
    Also, The contents are masterwork. you’ve done a great process in this topic!

  40. You’re so awesome! I do not believe I’ve truly read through something like that before.
    So wonderful to discover somebody with some original thoughts on this
    subject matter. Really.. thanks for starting this up. This site is one thing that’s needed on the web, someone with a
    little originality!

  41. Simply want to say your article is as surprising.
    The clearness to your publish is just spectacular and that i can assume
    you’re an expert in this subject. Well along with your permission let me to
    snatch your feed to keep updated with drawing close post.
    Thanks one million and please continue the gratifying work.

  42. I think that is one of the so much important information for me.
    And i’m glad reading your article. But should remark on some
    normal things, The site taste is ideal, the articles is in reality excellent :
    D. Just right job, cheers

  43. Greetings from Idaho! I’m bored to death at work so I
    decided to browse your website on my iphone during lunch break.

    I really like the info you present here and can’t
    wait to take a look when I get home. I’m shocked at how quick your
    blog loaded on my mobile .. I’m not even using WIFI, just 3G ..
    Anyhow, wonderful blog!

  44. Greetings from California! I’m bored to tears at work so I decided
    to browse your blog on my iphone during lunch break.
    I enjoy the information you provide here and can’t wait to
    take a look when I get home. I’m amazed at how fast your blog loaded on my cell phone ..

    I’m not even using WIFI, just 3G .. Anyhow, superb site!

  45. Nice post. I learn something new and challenging on websites I stumbleupon on a daily basis.
    It’s always exciting to read content from other authors and practice a little something from their websites.

  46. Very nice post. I just stumbled upon your weblog and wished to say that I
    have really enjoyed surfing around your weblog posts. In any case I’ll be subscribing on your feed and I am hoping you write once more soon!

  47. Link exchange is nothing else however it is only placing the other
    person’s webpage link on your page at proper place and other person will also do similar for you.

  48. Hey there! This post could not be written any better!
    Reading through this post reminds me of my good old
    room mate! He always kept talking about this.
    I will forward this article to him. Pretty sure he will have a good read.

    Thank you for sharing!

  49. Hello! Do you know if they make any plugins to safeguard against hackers?
    I’m kinda paranoid about losing everything I’ve worked hard on. Any
    suggestions?

  50. Howdy just wanted to give you a quick heads up. The text in your content seem to be running off the
    screen in Chrome. I’m not sure if this is a formatting issue or something to do with
    web browser compatibility but I thought I’d
    post to let you know. The style and design look great though!
    Hope you get the problem resolved soon. Kudos

  51. Pretty section of content. I just stumbled upon your blog
    and in accession capital to assert that I get in fact
    enjoyed account your blog posts. Anyway I will be subscribing to your augment and even I
    achievement you access consistently rapidly.

  52. You can certainly see your skills within the article you
    write. The arena hopes for even more passionate writers such
    as you who aren’t afraid to say how they believe. Always follow your heart.

  53. Hi just wanted to give you a brief heads up and let you know a few
    of the images aren’t loading properly. I’m not sure why but I think
    its a linking issue. I’ve tried it in two different internet browsers and both show the same outcome.

  54. May I just say what a relief to find someone that really understands what they’re
    discussing on the web. You actually understand how to bring a problem to light and make it
    important. More and more people should look at this and understand this side of the story.
    It’s surprising you are not more popular because you surely have the gift.

  55. hi!,I love your writing so a lot! percentage we keep in touch extra about your article on AOL?

    I need an expert on this house to resolve my problem.

    May be that is you! Having a look forward to see you.

  56. I am curious to find out what blog platform you happen to be utilizing?
    I’m experiencing some small security problems with my latest website and
    I would like to find something more risk-free. Do you
    have any suggestions?

  57. Having read this I thought it was really enlightening.

    I appreciate you taking the time and energy to
    put this short article together. I once again find myself spending a lot of time both reading and leaving comments.

    But so what, it was still worth it!

  58. Do you mind if I quote a few of your articles as long as
    I provide credit and sources back to your blog?

    My website is in the exact same area of interest as
    yours and my visitors would certainly benefit from
    some of the information you present here. Please let me know if this ok with you.
    Many thanks!

  59. However, the powerful techniques of a blog writing service are usually ignored and underestimated.
    We’re glad to answer questions in writing and on the phone.
    Serious questions. And we began to consider.
    I first discovered the joys of blogging back
    in 2007 when I started my Crafting 365 project to be
    crafty every day and blog about my progress. For instance the player restart from the scene
    of death, but lose precious resources, gain some kind of injury or just be transported back to bed with any progress intact.
    Looking back on which areas worked in Penumbra, this component became apparent.
    Remember Rita? I was yelling for her last year! The Last of
    Us is the big storytelling game of 2013. Here is a collection of thoughts on what can be learned from it.

    Two of the most popular are Facebook and Twitter, not only do you build up a following and a crew of regular readers
    you can also generate tons of traffic.

  60. I got this web page from my friend who told me about this
    web page and at the moment this time I am visiting this web page and
    reading very informative content here.

  61. hello!,I really like your writing so so much! proportion we
    communicate extra approximately your article on AOL? I require an expert on this house to resolve my problem.
    May be that is you! Having a look ahead to look you.

  62. Hi there! I’m at work browsing your blog from my new iphone
    3gs! Just wanted to say I love reading through your blog and look
    forward to all your posts! Carry on the outstanding work!

  63. you are really a good webmaster. The site loading pace is
    amazing. It kind of feels that you’re doing any unique
    trick. Moreover, The contents are masterwork.
    you’ve performed a magnificent process in this topic!

  64. Hey there just wanted to give you a quick heads up. The text in your
    article seem to be running off the screen in Safari. I’m not sure
    if this is a format issue or something to do
    with web browser compatibility but I thought I’d
    post to let you know. The style and design look great though!
    Hope you get the problem solved soon. Thanks

  65. Hello there! This is my first visit to your blog! We are a collection of volunteers and starting
    a new initiative in a community in the same niche.
    Your blog provided us useful information to work on.
    You have done a outstanding job!

THOÁT KHỎI BÌNH LUẬN

Please enter your comment!
Please enter your name here