C sort an array 💱

Поділитися
Вставка
  • Опубліковано 14 жов 2024

КОМЕНТАРІ • 74

  • @BroCodez
    @BroCodez  3 роки тому +63

    #include
    void sort(char array[], int size)
    {
    for(int i = 0; i < size - 1; i++)
    {
    for(int j = 0; j < size - i - 1; j++)
    {
    if(array[j] > array[j+1])
    {
    int temp = array[j];
    array[j] = array[j+1];
    array[j+1] = temp;
    }
    }
    }
    }
    void printArray(char array[], int size)
    {
    for(int i = 0; i < size; i++)
    {
    printf("%c ", array[i]);
    }
    }
    int main()
    {
    //int array[] = {9, 1, 8, 2, 7, 3, 6, 4, 5};
    char array[] = {'F', 'A', 'D', 'B', 'C'};
    int size = sizeof(array)/sizeof(array[0]);
    sort(array, size);
    printArray(array, size);

    return 0;
    }

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

      Thanks a lot for your brief, well and precise explained tutorial. 2 questions I still have:
      why you used 2 for-loops and in consequence 2 different variables for each " i, j "?
      why exactly did you write in the loop conditions a '-i' at 03:25 ?
      I'd be grateful if you could explain it a bit in details.

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

      #include
      void sorter (int array[], int size)
      {
      for(i = 0; i < size -1 ;i++)
      {
      for (j = 0; j < size - 1; j++)
      {
      if(array[j] > array[j+1])
      { int temp = array[j]
      array[j+1] = array[j]
      int temp = array[j+1]
      }
      }
      }
      }
      void printsort(int array , int size)
      {
      for(i=0,i < size, i++)
      {
      printf("%d",array[i]);
      }
      }
      int main()
      {
      int array[] = {1,9,6,7,8,3,4,5,2,0};
      int size = sizeof(array)/sizeof(array[0]);
      sorter(array[], size)
      printsort(array,size)
      return 0
      }
      Bro this not working

  • @GameHub-o4m
    @GameHub-o4m 3 місяці тому +8

    for (int i = 0; i < size - 1; i++)
    for (int j = 0; j < size - i - 1; j++)
    Example Walkthrough with Array [5, 3, 8, 4, 2]
    Initial State of the Array:
    [5, 3, 8, 4, 2]
    First Pass (i = 0):
    Outer loop starts with i = 0.
    Inner loop runs with j ranging from 0 to 3 (size - i - 1 = 5 - 0 - 1 = 4).
    Comparisons and swaps within this pass:
    j = 0: Compare 5 and 3, swap → [3, 5, 8, 4, 2]
    j = 1: Compare 5 and 8, no swap → [3, 5, 8, 4, 2]
    j = 2: Compare 8 and 4, swap → [3, 5, 4, 8, 2]
    j = 3: Compare 8 and 2, swap → [3, 5, 4, 2, 8]
    End of first pass: largest element 8 is at the end.
    Second Pass (i = 1):
    Outer loop continues with i = 1.
    Inner loop runs with j ranging from 0 to 2 (size - i - 1 = 5 - 1 - 1 = 3).
    Comparisons and swaps within this pass:
    j = 0: Compare 3 and 5, no swap → [3, 5, 4, 2, 8]
    j = 1: Compare 5 and 4, swap → [3, 4, 5, 2, 8]
    j = 2: Compare 5 and 2, swap → [3, 4, 2, 5, 8]
    End of second pass: second largest element 5 is in position.
    Third Pass (i = 2):
    Outer loop continues with i = 2.
    Inner loop runs with j ranging from 0 to 1 (size - i - 1 = 5 - 2 - 1 = 2).
    Comparisons and swaps within this pass:
    j = 0: Compare 3 and 4, no swap → [3, 4, 2, 5, 8]
    j = 1: Compare 4 and 2, swap → [3, 2, 4, 5, 8]
    End of third pass: third largest element 4 is in position.
    Fourth Pass (i = 3):
    Outer loop continues with i = 3.
    Inner loop runs with j ranging from 0 to 0 (size - i - 1 = 5 - 3 - 1 = 1).
    Comparisons and swaps within this pass:
    j = 0: Compare 3 and 2, swap → [2, 3, 4, 5, 8]
    End of fourth pass: fourth largest element 3 is in position.
    After these passes, the array is sorted: [2, 3, 4, 5, 8].
    Summary
    i: Controls the number of passes. Each pass ensures the next largest unsorted element is moved to its correct position at the end.
    j: Controls the comparisons within each pass. Its range decreases with each pass as the largest elements are sorted to the end.
    Bubble Sort Mechanism: The largest unsorted element "bubbles up" to its correct position during each pass of the outer loop.
    Visualization
    Initial Array: [5, 3, 8, 4, 2]
    After Pass 1: [3, 5, 4, 2, 8]
    After Pass 2: [3, 4, 2, 5, 8]
    After Pass 3: [3, 2, 4, 5, 8]
    After Pass 4: [2, 3, 4, 5, 8]
    The sorted array is achieved after these passes, demonstrating how i and j control the sorting process.

    • @PSGL0417
      @PSGL0417 3 місяці тому

      Thanks bro! Great explanation!

    • @furuguma
      @furuguma 2 місяці тому

      Thank you!

  • @GameHub-o4m
    @GameHub-o4m 3 місяці тому +5

    If you do not use the condition j < size - i - 1 in the inner loop and the outer loop does not run until i < size - 1, the program will not sort the array correctly. Here's what will happen in different scenarios:
    Inner Loop Without j < size - i - 1
    If you use the condition j < size instead of j < size - i - 1 in the inner loop, you will encounter two primary issues:
    Out-of-Bounds Access: When j reaches size - 1, array[j + 1] will access an element beyond the end of the array, leading to undefined behavior.
    Inefficiency: The inner loop will make unnecessary comparisons and swaps even after the largest elements have bubbled to the end of the array.
    Outer Loop Without i < size - 1
    If you use the condition i < size instead of i < size - 1 in the outer loop, the program will make an unnecessary extra pass through the array. This extra pass won't harm the correctness but will reduce efficiency slightly.

  • @blenderofficial139
    @blenderofficial139 3 роки тому +54

    Bro code, I had learnt python,html/css, JavaScript and now currently learning this beautiful playlist of c language . Thanks man
    May God bless you with more knowledge

    • @DaEpicKiller
      @DaEpicKiller 2 роки тому +6

      nice bro, you are now a true bro coder

    • @chatgpt-h9v
      @chatgpt-h9v Рік тому

      in how much time you learned all these courses

  • @brucebergkamp
    @brucebergkamp Рік тому +10

    @03:29, you added -i to j < size -1 .. the result came out the same with or without the -1 . What do you mean by optimize? WIll it affect other things with or without optimization?

    • @epitaph20
      @epitaph20 Рік тому +3

      same question here

    • @zraie2455
      @zraie2455 10 місяців тому +21

      optimize: put less load on the program by removing redundant(unneeded) processes.
      When he does j < size - i - 1, he is basically reducing the amount of elements that he needs to check, I'll show you what I mean by example.
      1. At start of loop, when i = 0, j = 0, here's what the array looks like:
      {9, 1, 8, 2, 7, 3, 6, 4, 5}
      2. After one iteration of j (i = 0, j = 1), the array will look like this:
      {1, 9, 8, 2, 7, 3, 6, 4, 5}, the 9 has essentially moved to the right of 1, because it satisfies the condition of the if statement within the 2nd for loop (i.e. 9 > 1)
      3. After 2 iterations of j (i = 0, j = 2), it will look like this:
      {1, 8, 9, 2, 7, 3, 6, 4, 5}, i.e. 8 and 9 have been swapped for the same reasons mentioned in step 2.
      4. Similarly after all iterations of j have been finished for the case where i = 0 (i = 0, j = 8), it will look like this
      {1, 8, 2, 7, 3, 6, 4, 5, 9}, basically extending the reasoning from step 2 to all cases of j in one go.
      5. Now for the first iteration of i, steps 1-4 are repeated again, however j is capped at 7 (as opposed to 8, because the for loop has condition j < size - i - 1), this is what it would look like at i = 1, j = 7:
      {1, 2, 7, 3, 6, 4, 5, 8, 9}, Notice how the 9 is unchanged? This is because Bro coded the algorithm in such a way that the largest number of the array will always be the last element of the array (and hence the 2nd largest would be 2nd last, and 3rd largest would be 3rd last, etc...). This means we essentially don't need to check for the last number of the array as it is definitely larger than the element we are currently checking (at i = 1), and similarly we don't need to check for the last 2 numbers of the array as they are definitely larger than the element we are currently checking when i = 2.
      Bro simply expresses this such that the computer can understand by typing j < size - i - 1, where i is the last n elements we already put at the end of the list (that we don't need to check anymore). This may not be useful for such a small program, but suppose the array had 5000 elements, You would save so much operating time by not having to check all 5000 elements every iteration.

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

      Basically bro the size is the same amount of loops the for will undergo so if u have 9 numbers by the 8th loop all the numbers will be sorted so to get rid of the last unnecessary loop size - 1 do the job

  • @prumchhangsreng979
    @prumchhangsreng979 2 роки тому +17

    what is the reason for size-1? is it because we only compare up to the last 2 element? if we go one more, the last element wouldn't have anything to compare itself to??

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

      + ive been lookin for an answer to this too

    • @juanzan_9599
      @juanzan_9599 2 роки тому +8

      Hey! I was thinking the same thing. I think it is because you don't need to sort the last item. If all the other numbers are in their place, the finishing integer will also be in its place.

    • @leopettecrew5695
      @leopettecrew5695 2 роки тому +17

      If we did it up to size, we would get an out of bounds error. As the element after the last element does not exist.

    • @dream_makers
      @dream_makers Рік тому +4

      ua-cam.com/video/YqzNgaFQEh8/v-deo.html this video will help you understand the reason if you still want to know

    • @raffstd
      @raffstd 10 місяців тому +1

      The elements 1-9 are actually counted (indexed) from 0. So 0-8 here (0 is the first and 1 is the second etc. so if n = 9 the last index is 9-1, 8. I think lol!

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

    Many thanks for the video.
    Why Line 5 and 7 for codition: i < size -1
    and Line 21 for condition: i < size

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

      bubble sort algorithm : swap two element in the order, loop to all of elements in the array sorted

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

      from what I understood, a computer counts from 0, so if we have array[ ] = {1, 2, 3}; the size is obviously 3, while the last element is actually array[2] = 3.
      Hope I made a bit of sense lol

  • @sakai2372
    @sakai2372 11 місяців тому +1

    You are my life saver. Thank you.

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

    is the size variable important?

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

    Here's a bubble sort I made:
    #include
    #include
    #include
    #include
    #include
    void bubbleSort(int myArray[], int arraySize);
    void printArray(int myArray[], int arraySize);
    int main(){
    int myArray[] = {1,3,5,11,12,800,2,6,4,8,9,10,17,7};
    int arraySize = sizeof(myArray)/sizeof(myArray[0]);
    bubbleSort(myArray , arraySize);
    printArray(myArray , arraySize);
    return 0;
    }
    void bubbleSort(int myArray[], int arraySize){
    int temporary;
    for(int i = 0; i < arraySize - 1; i++){
    for(int j = 0; j < arraySize - 1 - i; j++){
    if(myArray[j] > myArray[j+1]){
    temporary = myArray[j];
    myArray[j] = myArray[j+1];
    myArray[j+1] = temporary;
    }
    }
    }
    }
    void printArray(int myArray[], int arraySize){
    for(int i = 0; i < arraySize; i++){
    printf("%d
    ",myArray[i]);
    }
    } // This was incredibly easy for me because I already watched brocode's c++ videos and this is basically the same thing.

    • @stnoverheaven4952
      @stnoverheaven4952 6 місяців тому

      Why do we need the nested loop though ( ik without it the loop would be incompleted ).
      I dont understand the logic behind the numbers of time why we need to redo the Swapping loops

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

    Did an ascending order and the first few index has random values and my inputted values are sorted starting approximately from the middle of the array size.

  • @SyamsidvilasAvvaru
    @SyamsidvilasAvvaru 24 дні тому

    Super😊

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

    Do you also have a video for counting sort?

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

    your videos are great keep going .

  • @CS_Mustcode
    @CS_Mustcode Рік тому +3

    in swap section ,why don't we use this ( array[j] ^= array[j + 1] ^= array[j] ^= array[j + 1]; ) instead of this /*
    int temp = array[j];
    array[j] = array[j+1];
    array[j+1] = temp;
    */

  • @stnoverheaven4952
    @stnoverheaven4952 6 місяців тому

    I dont really understand why we needed a nested loop ( without it the loop will be messed up )

  • @PoptartWisard
    @PoptartWisard Рік тому +4

    Hey I was wondering how you are able to modify an array inside a function and pass it to the next function without returning the modified array from the first, if someone could explain, that would be dope.

    • @francescob1904
      @francescob1904 8 місяців тому

      Hi, for what i learnt so far when you pass an array in a function you are indeed passing the adress of the 0th element of the array (the first one) so you're not creating a new array inside the function but you're referring to the same array you have in the main.

  • @najmulislam6518
    @najmulislam6518 7 місяців тому

    Thanks a lot Bro.

  • @Ava-x9z3n
    @Ava-x9z3n 2 місяці тому

    How do you know so many programming languages?

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

    I did not understand why the for loop goes from 0 to size-1 with strict disequality, this means it goes from 0 (first element) to the n-2 element since if size = 5 elements of the array goes from index 0 to 4 so size-1=4 but with the "

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

      @Benjamín Ramírez Puyol yea you're right, the reason of My confusion Is that I Always did the quicksort with a discendent for loop inside an ascendent for loop where i goes from 1 to n-1 and j from i to 0

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

      Basically bro the size is the same amount of loops the for will undergo so if u have 9 numbers by the 8th loop all the numbers will be sorted so to get rid of the last unnecessary loop size - 1 do the job

  • @vsots
    @vsots 8 місяців тому

    How were you able to get away with having temp still as an integer when the data type being swapped is char?

    • @1kvolt1978
      @1kvolt1978 4 місяці тому +1

      Because char actually is an integer of size 1 byte. It fits in the int type, which in this case is size of 4 bytes, with no problem.

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

      @@1kvolt1978 Thank you!

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

    Thankyou very much bro ☺🤜🤛

  • @KTL-rs7ge
    @KTL-rs7ge 3 роки тому +1

    Hey Bro, what is this kind of sort name?

  • @gigachad724
    @gigachad724 10 місяців тому +1

    //Thank u Bro Code
    //my version with user input :
    #include
    #include
    main()
    {
    int array[10];
    printf("enter 10 numbers!
    ");
    for(int k =0;k

    • @subhamsingh7627
      @subhamsingh7627 9 місяців тому

      why did you find the size of array, we already knew its 10

  • @neerajpatil3736
    @neerajpatil3736 8 місяців тому

    thank you

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

    Line 12 and 13 at 4:07 of the video. Why do I get a warning for using strcpy()?

    • @PSIwolf39
      @PSIwolf39 10 місяців тому +1

      It could be possible that you forgot to add the string header.
      if you don't have "#include " at the top of your code then "strcpy()" will never work.

    • @1kvolt1978
      @1kvolt1978 4 місяці тому

      Because this function is unsafe and is not recommended to use. Use strncpy() instead.

    • @1kvolt1978
      @1kvolt1978 4 місяці тому

      @@PSIwolf39 If there is no header added there would be an error, not a warning.

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

    i am not a profecinal coder but i think there is no need of i loop

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

    Thanks for being awesome

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

    ❤️

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

    bro is code like a GigaChad ...

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

    _Thx bro_

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

    pls u are too fast for beginners like me, but still thanks ur vid is great

  • @roronoazoro5672
    @roronoazoro5672 22 дні тому

    can somebody please tell me why did he introduce another function(printarray)

    • @Omantonkiyamat
      @Omantonkiyamat 15 годин тому

      So his main function become more easy to understand

    • @Omantonkiyamat
      @Omantonkiyamat 15 годин тому

      So rather than cop paste every single print in main function he just call the function print

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

    well it doesnt work on me... I have writen all the logical stuff and it doesn't sort correctly. So I straight up copied your code to my text editor and still doesn't work. If you can help me id appreciate it a lot... (check the replies on the comment :) )

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

      I had the same issue even though it was able to run my code a week before. Try this:
      1. CTRL+SHIFT+X
      2. Type in search box Code Runner
      3. Install the extension
      4. Then click on File - Preferences - Settings
      5. Type code run in search box.
      6. Scroll down until you find Code-runner: Run In Terminal. Check the box Wheather to run code in Integrated Terminal.
      7. Restart VS Code
      I already had a code runner installed so I skipped to steps 6 and 7. Hope this helps!

  • @unclek953
    @unclek953 11 місяців тому

    i'm still dont understand why do we have to minus 1 the size on the funtion... can someone help me plss

    • @zraie2455
      @zraie2455 10 місяців тому +1

      Arrays count indexes by starting on 0. Imagine if an array had 3 elements. The first element would be array[0], the second element is array[1], and the third element is array[2], there is no such thing as array[3] because it is "out of bounds" of the array. Hence we have to do size - 1 so the program doesn't return an out of bounds error.

    • @unclek953
      @unclek953 9 місяців тому

      @@zraie2455 aye i figured it out already but thank you for helping me!!, i didn't expecte to have an answer from someone from the start ❤

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

    //different version (with int)
    #include
    void sort(int array[], int size){
    int temp, flag;
    do {
    flag = 0;
    for (int i = 0; i < size - 1; i++) {
    if (array[i] > array[i + 1]) {
    temp = array[i];
    array[i] = array[i + 1];
    array[i + 1] = temp;
    flag = 1;
    }
    }
    } while (flag == 1);
    }
    void printArray(int array[]){
    for (int i = 0; i < 5; ++i) {
    printf("%d ", array[i]);
    }
    }
    int main() {
    int numeros[5] = {5, 3, 9, 18, 1};
    int size = sizeof(numeros)/ sizeof(numeros[0]);
    printf("Array before sort: ");
    printArray(numeros);
    sort(numeros, size);
    printf("
    Array after sort: ");
    printArray(numeros);
    return 0;
    }
    😁

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

    bro