Bubble sort algorithm

Поділитися
Вставка
  • Опубліковано 6 вер 2024
  • See complete series on sorting algorithms here:
    • Sorting Algorithms
    This series is in progress, we will be adding lessons into this series every week.
    In this lesson, we have described Bubble sort algorithm and analyzed its time complexity.
    Series on Time Complexity:
    • Time Complexity Analysis
    Subscribe to our channel to get updates on new lessons.
    You may also like us on Facebook:
    / mycodeschool

КОМЕНТАРІ • 410

  • @FRSS27
    @FRSS27 4 роки тому +106

    Finally, a tutorial explaining not only the logic of the algorithm, but the logic behind it's iteration. Thanks a bunch!

  • @sriharshasaraswathula6127
    @sriharshasaraswathula6127 6 років тому +8

    The outer loop must execute from 0 t0 n-1, otherwise last element will not be sorted.
    code:
    for(int k=0;k

  • @blueskyrelaxmusic
    @blueskyrelaxmusic 7 років тому +84

    This is what we need in youtube. Great lecture with great timing.Good job.

  • @ibzih
    @ibzih 3 роки тому +29

    Dude this 10 mins video is worth my uni's multiple hour lectures. Very helpful! Thanks!

  • @allblue7027
    @allblue7027 5 років тому +145

    i swear this is way better than some of the professors video in schools

    • @crazy-maxedout8512
      @crazy-maxedout8512 3 роки тому +2

      on the gang!

    • @khoitan4758
      @khoitan4758 2 роки тому +1

      I think I have a short attention span and I can get tired very quickly. And direct teaching in school is just too slow for me as teachers just try to explain every single detail. Most UA-cam videos are just short and have enough information so I understand them almost immediately.

    • @zerospectator4119
      @zerospectator4119 2 роки тому +3

      Mine just straight up doesn't teach anything

    • @shankar7435
      @shankar7435 Місяць тому

      100% true.❤❤❤

  • @ANILKHANDEI
    @ANILKHANDEI 4 роки тому +6

    The video is perfect. Thanks for the ultimate collection. One check is that outer loop runs n-1 times and inner loop is an arithmetic progression n*(n-1)/2 instead of n-1. The total being n+ (n*(n-1)/2= O(n^2). Just wanted to point out. Let me know if my consideration is wrong.

  • @curiouswithAi
    @curiouswithAi 5 років тому +4

    This channel is a true Gem For Students. Got an exam tomorrow. Would have been really difficult without You. Thank You so much for this!!!!!

  • @thatswhatsup0493
    @thatswhatsup0493 10 років тому +104

    Thanks so much! subscribed! This is so much more helpful than my text book :D

    • @mycodeschool
      @mycodeschool  10 років тому +18

      thatswhatsup0493 You are most welcome :)

    • @PhaniKatakam
      @PhaniKatakam 7 років тому

      Thanks Bro! Nice efforts.. and I like the variations you explained how we improve with flag...etc../\

    • @gauravlotekar660
      @gauravlotekar660 7 років тому +2

      boss i feel like dumb dumb dumb when u talk about big(o).I need more help with it.Any suggestions?

  • @mycodeschool
    @mycodeschool  11 років тому +54

    Hi Ravi,
    I guess you are talking about 6:03. Outer loop is running from 1 to n-1 (we could have run from 0 till n-2 also) which is n-1 times. If you bubble up n-1 elements, last one - nth one will automatically be in place. So, no need to run n time. Inner loop is running from 0 till n-2. It's again n-1 times. So, it looks correct to me.

    • @farooqabbasi9674
      @farooqabbasi9674 3 роки тому

      O

    • @markosavic4544
      @markosavic4544 3 роки тому +1

      Line where first for is will be executed n times,not n-1

    • @vinhnguyen-o5z
      @vinhnguyen-o5z 2 роки тому +3

      back when youtube didn't have the reply feature huh

    • @ganeshk8682
      @ganeshk8682 2 роки тому

      May is confusion with looping where less than symbol. < n- 1 is nothing but up to n-2 inclusive
      int[] arr = {0, 2, 1, 2, 0};

      int n = arr.length, temp;
      for(int k=0; k< n - 1; k++ ) {
      for (int i = 0; i < n - 1; i++) {
      if (arr[i] > arr[i + 1]) {
      temp = arr[i];
      arr[i] = arr[i + 1];
      arr[i+1] = temp;
      }
      System.out.println(Arrays.toString(arr));
      }
      }

    • @jobearnest
      @jobearnest 2 роки тому +4

      @Ganesh K in ur prgm second loop can be optimised like: for(int i=0;i

  • @manishasharma-hy5mj
    @manishasharma-hy5mj 10 років тому +58

    Thank you so much for the series of sorting algorithms.
    I request you to give explanation on heap sort.

    • @harshalberad5957
      @harshalberad5957 5 років тому +1

      You have to learn tree chapter first if you want to learn heap sort

    • @peterandreash2841
      @peterandreash2841 4 роки тому

      Search for "udiprod" on UA-cam, they have a great explanation.

  • @ishanpand3y
    @ishanpand3y 5 років тому +2

    I think outer loop shouldn't start with one because if k won't be starting at zero then the inner loop will go only n-k-1 i.e if k = 1 it'll go up to n-2 times if there's a small variable at the end of the array then it won't be able to reach the end to compare as it'll end one before the last one. For example this below code :
    // bubble - sort
    class BubSort{
    void sorting(int A[],int n){
    for(int k = 1 ; k < n - 1 ; k + + ) {
    boolean flag = false;
    for (int i = 0 ; i < n - k - 1 ; i + + ) {
    if (A [ i ] > A [ i + 1 ] ) {
    int temp = A [ i + 1 ] ;
    A [ i + 1 ] = A [ i ] ;

    A [ i ] = temp;
    flag = true;
    }
    }
    if (flag == false) break;
    }
    for ( int i = 0 ; i < n ; i + + ) {
    System.out.println(A [ i ] ) ;
    }
    }
    public static void main(String...ssg){
    int A[] = {42,23,54,76,23,6,34,8,4,2,3,1};
    BubSort b1 = new BubSort();
    b1.sorting(A,A.length);
    }
    }
    output - 2 3 4 6 8 23 23 34 42 54 76 1

    • @aparnamane2846
      @aparnamane2846 5 років тому

      right also flag variable when included and unsorted array is passed the output obtained is not correct

  • @mauriceudoh7243
    @mauriceudoh7243 9 років тому +45

    This is simplified enough for a comprehension, Thanks !!!!!!!

  • @minimalist_pc
    @minimalist_pc 7 років тому +9

    your explanation is perfectly clear and the coding is really simple. Thank you so much!

  • @viditsinghbrahmania1476
    @viditsinghbrahmania1476 4 роки тому +1

    I can not even fathom how much effort would be needed to make something like this, and it is freely available!
    I don't know if any of you have noticed, but he is using MS Paint. And I didn't know it could ever be used to make something useful, let alone this.
    I always used to undermine myself, considering that I am not a 'programmer'(never really understood these simple concepts, due to shitty teachers), but in the last few weeks, I've learnt so much only because of you and other good content on the internet. And now I proudly say I enjoy programming and I am a programmer!

  • @chelseakatsidzira7153
    @chelseakatsidzira7153 5 років тому +7

    very helpful thank you so much. this is honestly the most clear cut explanation on youtube

  • @saltyfish157
    @saltyfish157 7 років тому +18

    You are the best explainer I have ever seen

  • @ahinsa__parmo__dharam
    @ahinsa__parmo__dharam 3 роки тому +1

    When you reach for O(n), i'm shocked because I had never seen this version of bubble sort .. hatsoff to you.

  • @anchitbhushan6172
    @anchitbhushan6172 5 років тому +4

    @9:19 i think the inner loop will be executed n-1 times when there is an already sorted array as input

  • @zhangjing1992
    @zhangjing1992 8 років тому +1

    question in 9:05(I feel it should be like this ): if(flag == 1) break ;
    not even one swap if flag ==0; then doesn't that mean we need to swap?

  • @preetshah6955
    @preetshah6955 2 роки тому

    This is the best channel for learning algorithm and data structure. I am coming back here after 5 years

  • @akhilgupta3664
    @akhilgupta3664 4 роки тому +6

    Brilliant explanation !! Need teachers and mentors like you , that will change the whole learning process !!
    Thanks 😀✌️

  • @maheshvalikar2788
    @maheshvalikar2788 7 років тому +15

    You are the best presenter i have ever seen. Very much useful. This kind of tutorials what we expect. Great job bro.

  • @AshChaudhari
    @AshChaudhari 7 років тому +10

    i think u made mistake... A[0,1,2,....n-1]
    for i

  • @thePrinceOfPurpose
    @thePrinceOfPurpose 5 років тому +10

    Actually, if you start from 0 and your size of the array is n. Then n-1 will allow you to go to a[i+1]. You're missing an element if you only go to n-2.

  • @ravs
    @ravs 5 років тому +8

    Your explanation is by far the best. I wish I could explain to my students in a similar fashion. Keep posting. Good work.

  • @ezechielmusic
    @ezechielmusic 6 років тому +6

    maybe i'll teach my prof tomorrow , thank you bro , it was really clear. :)

  • @Shailendrakumar-ge5cf
    @Shailendrakumar-ge5cf 2 роки тому +1

    Even it is 9 year old . This video was very helpful.
    Thanks for sharing you've got a new subscriber :)

  • @cagnusmarlsen4050
    @cagnusmarlsen4050 4 роки тому

    In all of the videos the voice and the language is pretty clear and sharp so there's no need for sub-titles.

  • @VinayYadav-pl7xw
    @VinayYadav-pl7xw 8 років тому +6

    Great explanation..... Exactly what tiny brains like me required :)

  • @outofonesmind6722
    @outofonesmind6722 6 років тому +2

    The first loop should be from k= 0 to (n-1) right??

  • @CompilerStuck
    @CompilerStuck 2 роки тому +1

    I feel like being back in school reading stuff on the almighty overhead projector

  • @pramodkajla
    @pramodkajla 5 років тому +1

    Best explanation on bubble sort. I have checked out lot of videos but, I was still not clear about the concept. Finally, this video helped me. Thank you so much. Excellent work.

  • @joecoke6925
    @joecoke6925 8 років тому +1

    Really smart to focus on constructing the inner-loop first. It really makes everything more clear.

  • @LLLLLLEON216
    @LLLLLLEON216 8 років тому +4

    Much better than my prof's lecture! Thanks!

  • @UNUNUN11
    @UNUNUN11 10 років тому +5

    nice explamnation
    I am taking Master in Computer Science
    I will have a course Advance Alogrithms
    so I am reviewing some sort algorithms

  • @shreyasinghthakur2862
    @shreyasinghthakur2862 4 місяці тому

    For people wondering why n-2 and not n-1 -----
    Explaination - In an array, "n" typically represents the total number of elements in the array. So, "n-1" would refer to the index of the last element in the array since array indexing usually starts from 0.
    For example, let's say we have an array with 5 elements. "n" would be 5, and "n-1" would be 4, representing the index of the last element in the array. So if we have an array called `arr`, `arr[4]` would be the last element.

  • @ahsantahirprogramming
    @ahsantahirprogramming 3 роки тому

    Your Chanel Is Best For Pograming

  • @goldenotis9703
    @goldenotis9703 6 років тому

    Best big o notation explanation I've seen so far and its not even a big o analysis video

  • @ShahidulIslam-qd2mv
    @ShahidulIslam-qd2mv 5 років тому +4

    Nice presentation. Thanks a lot. Seems like, learned bubble sort newly after completing graduation about 10 years ago.
    One thing, at 9:45 will it break the inner loop or outer? Sorry for my ignorance.

    • @aLogicalNut7
      @aLogicalNut7 4 роки тому +1

      The outer loop. That if condition should be placed after the inner loop.

  • @piaNegi
    @piaNegi 4 місяці тому +2

    Thank you sir for explanation ❤️
    But what made me comment here is
    You sound exactly like a krsn katha vachak (i don't remember his name)

  • @shobhitranjan3957
    @shobhitranjan3957 4 роки тому +1

    Brilliant explanation of BUBBLE SORT so far!

  • @KETKIPATILBCE
    @KETKIPATILBCE 4 роки тому +1

    Thank you very much....this code I was trying to mug up ..now you made it's concept really simple and understandable

  • @davidnovosardian6848
    @davidnovosardian6848 7 років тому +3

    You explain it sooo much better than my professor, I don't know how my professor became a professor. OMG thank you

  • @kkoli
    @kkoli 2 роки тому

    this videos are much more better than the paid ones thank you sir you are really doing great work

  • @vaibhavnag1154
    @vaibhavnag1154 8 років тому +1

    thankyou so much my code school, it helped me a lot... it is much better than hand books... and through these videos it is easier to understand and remember all the things..
    Thank you

  • @harabe1sh1o
    @harabe1sh1o 9 років тому +28

    Great viddeo.
    A minor note that the loops look like this:
    for(int k = 1; k < size; k++)
    for(int i = 0; i < size - k; i++){

    • @emi.grigore
      @emi.grigore 7 років тому +9

      pseudocode and C++ are 2 diff things ;) so his loops are fine, because the title is bubble sort algorithm, not C++ program. No offense :D

    • @Jsheng007
      @Jsheng007 6 років тому

      Thanks man for the c++ for loop

    • @sanjanind
      @sanjanind 6 років тому +1

      watch till the end, he mentioned that.

    • @vikasrajput4204
      @vikasrajput4204 5 років тому

      U r ri8 I also noticed in b/w...there is a minor mistake (n-k-1) must bi replaced with (n-k) in the 2nd for loop..!!

    • @TechHints
      @TechHints 5 років тому +1

      @@emi.grigore any programming code is a sort of replica to their pseudo code, so we should not do logical error in writing pseudo code or it can hamper the chance of writing the correct code. No offence to any one.

  • @its4pg
    @its4pg 11 років тому +2

    Hi Animesh Sir,
    You are doing tremendous work.You explain very well, so far I have seen many videos in Algos & DS but these vids are the best one, small compact and fully explained !!
    All the very best for your mission, to literate the illiterate Engineering students.

  • @aniketpandey2007
    @aniketpandey2007 5 років тому

    If im not wrong sir, I believe you are trying to call an external swap() function in this code, and in that case a default call by value does not work, I think you should pass the values by reference, for the actual array to be sorted within the main() function. Hence it should be swap(&a[I],&a[I+1]).

  • @Touhid_CSE
    @Touhid_CSE 8 років тому +1

    Thanks, this tutorial is realy good. but i think there is a little mistake in first loop where the value of 'k' will be 0 (zero). plz check this input : 1 3 2 5 4

  • @Danger418
    @Danger418 6 років тому +1

    This would easily qualify for priced courses. Very good presentations.

  • @babandimuhdnasir7057
    @babandimuhdnasir7057 Рік тому +1

    What an incredible explanation

  • @rishibharadwaj68
    @rishibharadwaj68 3 роки тому +1

    Great explanation. Crisp, simple and to the point!!

  • @tushardev5135
    @tushardev5135 2 роки тому

    best videos i have ever found for dsa

  • @tharindudissanayaka
    @tharindudissanayaka 7 років тому +1

    in our language "Supiriiiii.....!!! "Great tutorial ... I've cleared many things............

  • @rnjnmhta.catomato
    @rnjnmhta.catomato 2 роки тому

    best video on bubble sort ,concise and clear

  • @Tankionlineandgold
    @Tankionlineandgold 2 роки тому

    Thanks a lot man i tried a lot pf vidoes to understand it and this is what helped me understand how it really works

  • @jalsacentre1040
    @jalsacentre1040 3 роки тому +4

    Remember this obsession
    Selection sort and bubble sort requires same no of comparisons n(n-1)/2
    But in worst case bubble requires n(n-1)/2 swap rather Selection required n-1 swap
    ..... in my one interview question was asked Like which Sorting Algorithm is best If we consider only Swapping in complexity?

  • @birukanley6586
    @birukanley6586 2 роки тому

    you are great you make me feel not just to understand rather to feel.

  • @mairajshariff1167
    @mairajshariff1167 4 роки тому

    I want solutions for below given problem, kindly help:
    1- Why are we interested in worst case analysis?
    2- What do you understand by rate of growth or order of growth? Why it is important in analysis of an algorithm?
    3- For following set of functions, indicate whether f = O(g), f = Ω(g), or both.
    1) f(n) = n − 10, g(n) = n + 10
    2) f(n) = 10n^2, g(n) = 3n^3 + n^2
    4- For f(n) = n^2 + 2n^3 − 100nlogn + 10, provide the simplest possible function g(n) such that f(n) = Θ(g(n)).
    5- Show that n log n is O(n^2) but that n^2 is not O(nlogn).
    6- Prove or disprove the following: √n = O(logn)
    7- Use a recursion tree to determine a good asymptotic upper bound on the following recurrences.
    1) T(n) = 2T(n − 1) + 1
    2) T(n) = 4T(n/2) + cn
    8- Consider the recursive binary search algorithm for finding a number in a sorted array.
    (a) Give recurrence for the worst-case running times of binary search algorithm.
    (b) Use a recursion tree to determine a good asymptotic bound for the recurrence tree.
    9- The ternary search algorithm locates an element in a list of increasing integers by successively splitting the list into three sub lists of equal (or as close to equal as possible) size, and restricting the search to the appropriate piece.
    (a) Give recurrence for the worst-case running time of the algorithm.
    (b) Use a recursion tree to determine a good asymptotic bound for the recurrence tree.
    10- Provide recurrence relation and a tight asymptotic bound for the following code.
    long power ( long x , long n )
    if ( n == 0 )
    return 1;
    else
    return x * power ( x , n−1);

  • @jatinagg8221
    @jatinagg8221 6 років тому

    Best channel for computer science student. Thanks for sharing knowledge to us🙏🙏

  • @zhangjing1992
    @zhangjing1992 8 років тому +1

    hi, just one small mistake: in 6:12 the T(n) = (n-1) * (n-2) * C ; I think that's your meaning there.

  • @freeman37
    @freeman37 2 роки тому

    Very good explanation and tutorial on time efficiency.

  • @compilerrun5516
    @compilerrun5516 3 роки тому +1

    According to views of this playlist seems like merge sort is a hot topic.

  • @swatiomar8603
    @swatiomar8603 3 роки тому

    Best explanation.... I am looking for such tutorial.... Thanks :) and keep it up...

  • @chiragsharma6261
    @chiragsharma6261 3 роки тому

    The given array is arr = {1,2,4,3}. Bubble sort is used to sort the array elements. How many iterations will be done to sort the array?
    ***How the answer comes out to be 4.***
    Detailed explanation would be appreciated.

  • @aviroxi
    @aviroxi 3 роки тому +1

    thank you so much for this series

  • @l.p.9568
    @l.p.9568 4 роки тому +2

    I think 6:14 should be cn^2 - 2cn + 1c. i.e., the last part is not 1, but 1c.

  • @ravibisla
    @ravibisla 11 років тому

    for inner loop t(n) should be C*(n)*(n-1) where n-1 is from outer loop and n is from inner loop itself?

  • @rickydonne802
    @rickydonne802 3 роки тому

    Hi ! Shouldn't the bubble sort algo in C look like this:
    void bubblesort(int A[], int n)
    {
    int k, i, flag, temp;
    for (k = 1; k < n; ++k)
    {
    flag = 0;
    for (i = 0; i < (n - k); ++i)
    {
    if (A[i] > A[i + 1])
    {
    temp = A[i + 1];
    A[i + 1] = A[i];
    A[i] = temp;
    flag = 1;
    }
    }
    if(flag == 0)
    break;
    }
    }
    k in the video ran till n - 1, but it should run till nth element if the last element is the lowest.

  • @anjalii1102
    @anjalii1102 2 роки тому

    Thanks for such depth explaination

  • @rajasekharguntreddi
    @rajasekharguntreddi 5 років тому

    Best presentation I have ever seen

  • @keitasshi
    @keitasshi 4 роки тому

    How to count primitive operations in the coding? Where to add the counter to count the primitive
    operations?

    • @ChipSqueax
      @ChipSqueax 4 роки тому

      There's a clear explanation to your question on my video here! ua-cam.com/video/D4eQtG6U21E/v-deo.html. If you want a detailed explanation, here's another video I made:ua-cam.com/video/8sVVBaF99Ho/v-deo.html

  • @smithcodes1243
    @smithcodes1243 8 років тому +37

    Oneth. Dayumm

    • @planesairbornebymalikclark2806
      @planesairbornebymalikclark2806 8 років тому +3

      Lol Haha I paused the video to see if anyone else noticed Haha

    • @madebyibrahim
      @madebyibrahim 7 років тому +14

      It's actually the correct term. Harvard teaches it.

    • @nomathic7672
      @nomathic7672 5 років тому +1

      @@madebyibrahim This isn't the proper context oneth is used though. Oneth on its own isn't a word, it's a suffix.

    • @dwaynevanhaeften4042
      @dwaynevanhaeften4042 5 років тому

      *A ray*

    • @flamingpheonix5231
      @flamingpheonix5231 4 роки тому

      @@planesairbornebymalikclark2806 lmao me toooo

  • @user-mb8ee9hc9r
    @user-mb8ee9hc9r Рік тому

    if a already sorted array is given, then time complexity will be O(1) ryt, why O(n)

  • @RutulRavalLDRP
    @RutulRavalLDRP 9 років тому

    Subscribed after looking only one video.
    Awesome explanations.

  • @azadprasad856
    @azadprasad856 5 років тому +1

    Why two loops? The upper one

  • @SmartProgramming
    @SmartProgramming 6 років тому

    awesome tutorial sir, thank you 👍👍

  • @alzyl6287
    @alzyl6287 6 років тому

    This is very useful video and easy to understand

  • @sumanturkiya4342
    @sumanturkiya4342 6 років тому

    Nice explanation but one request it would be better if you give some more knowledge about the algorithm for example which one is best in this case, which is best of all, less time taken increasing order algo etc please tell about all this things as well thank you

  • @redtree732
    @redtree732 10 місяців тому

    This is an amazing video. Bravo.

  • @payalparmar_
    @payalparmar_ 5 років тому

    The way u explain the algo is awsm!

  • @Red-bb6qj
    @Red-bb6qj 8 років тому

    Indexes counter in the for loop should all start from 0 and both should use n - 1.

  • @MuhammadRaqiburRahman
    @MuhammadRaqiburRahman Рік тому

    Thank you for the efficient lecture.

  • @jalpacj7813
    @jalpacj7813 4 роки тому +1

    Nice explanation!ur voice is osm😅

  • @ManjeetSingh-ee4zk
    @ManjeetSingh-ee4zk 7 років тому +2

    BEST EXPLAINATION !

  • @augustadjurnic1707
    @augustadjurnic1707 10 місяців тому

    Thank you for your nice explanation

  • @mcwho3
    @mcwho3 8 років тому +2

    Great implementation of the flag. It makes a major difference.

  • @animeshnayan1
    @animeshnayan1 11 років тому

    Hi Rakesh,
    You can choose to start with whatever. In the end, your code should not be buggy. The pseudo-code in this lesson is good. You can try it out in a real program.

  • @J4T375
    @J4T375 3 роки тому

    very simple and abstracted, thank you

  • @ryanimperial651
    @ryanimperial651 8 років тому

    What if the number in the first position is higher than the second position?

  • @lakshyachaturvedi2712
    @lakshyachaturvedi2712 3 роки тому

    Why have you taken n-2 as last step?

  • @biikaaa.6540
    @biikaaa.6540 2 роки тому

    how multiple passes are happening when for loop is made only for 1?!

  • @sureshseneviratne1841
    @sureshseneviratne1841 9 років тому +2

    Hello ,
    Thank you soo much for creating this video!!
    It makes sorting algorithms seem soo easy and very understanding .i subscribed !!!
    Thank you !!!

  • @akshayjain4777
    @akshayjain4777 9 років тому +2

    Feeling lucky to have found your channel!!!! Subscribed :D

  • @yogeshtiwari4058
    @yogeshtiwari4058 4 роки тому

    Sir, in best case analysis, the inner for loop runs (n-1 ) time and outer pass loop runs only 1 time. But you said inner loop runs once?

    • @mattagab2717
      @mattagab2717 4 роки тому

      Big O(n-1 + n-1) => big O(2n-2) => big O(2n) => big O(n) for best case

  • @archanareddy5310
    @archanareddy5310 4 роки тому

    I have a doubt at 6:55
    (n-1) *(n-1)*c=cn2+2cn+1 or cn2+2cn+c

  • @fasihurrehman8673
    @fasihurrehman8673 3 роки тому

    Excellent explanation ♥️♥️

  • @mirrormask7946
    @mirrormask7946 5 років тому

    Thanks for the simple explanation.

  • @nO_d3N1AL
    @nO_d3N1AL 8 років тому

    Excellent explanation!

  • @kasperkarelse8106
    @kasperkarelse8106 7 років тому +1

    very clear, thank you