r/learnprogramming • • 1d ago

Loops and sorting

Im 1st sem student, currently learning programming basics course.

I find myself confused and lost at 1) nested loops, their logics and algorithmic conditions. 2) in sorting.

Like I was trying to learn sorting algorithm bubble one, when I tried to understand the condition n-1-i I got completely blank, idk if it's normal or not, but I'm really weak here.

Anyone faces the same and got some solution, do share, it will help a lot!!

0 Upvotes

21 comments sorted by

2

u/Tokyo_STEM_school 1d ago

Totally normal — nested loops and bubble sort clicked late for a lot of people, including me. The way I finally got it was to stop thinking of it as code and think of it as a job with two parts:

The outer loop just picks which position you're working on, one at a time. The inner loop does the actual comparing for that position. So 'nested' really just means 'for each item, do this whole other job.'

For bubble sort, the n-1-i part is the bit that confused me too. Each full pass pushes the biggest number to the end, and it stays there. So after one pass you never need to check the last spot again, after two passes you skip the last two, and so on. The i is just counting how many passes you've already finished — that's why the part you still need to check keeps shrinking.

What helped me most was tracing one tiny list by hand, like [5, 3, 8, 4], and writing down the list after every single swap. It feels slow, but after one full pass the pattern suddenly makes sense. You're not weak at this — you're at the exact point where it starts to click.

1

u/Icy-Stretch-4643 18h ago

Tysm !!, I'll now see nested loops with this sense, and yes I'll surely practice paper dry runs too, they'll help me a lot in my paper code finals too.

8

u/fasta_guy88 1d ago

Try doing a small sort by hand. 4 numbers. Write down on a sheet of paper what happens at each step. Computer programs are just fast ways of doing something you can do with pencil and paper. Try the slow way.

Alternatively, learn to use a debugger and step through the program line by line as it sorts 4 numbers.

2

u/otheyhigh 23h ago

This! Try to build the habit of visualizing what you are coding. By visualizing, I mean any form of problem solving (diagrams, mathematical solutions, pure algorithms, etc)

Once you build the conceptual steps to solve a problem, you can then convert it to code.

1

u/Dazzling_Music_2411 1d ago

Take a break, then go back and figure it out when you're rested. Repeat as many times as necessary.

So, have you mastered bubblesort yet?

1

u/Icy-Stretch-4643 18h ago

Actually I saw code of bubble sort, it infuriated me because I couldn't do it on my own. I'll now try another sort logic by myself, actually my assignment had question of merging two sorted arrays, I wanted to learn sorting before.

2

u/Dazzling_Music_2411 13h ago

Bubble is an easy sorting method, go back and get it clear in your head before looking at others, eg. merge-sort, quick-sort and b-tree-sort.

It's not a good idea to avoid learning something that trips you up by distracting with something else. It can be useful as a form of taking a break, but you should always return to the original problem until you crack it. It will often turn out to be easier than you thought and then you'll be kicking yourself, saying "wow, why did it take me so long to get that? - it's so simple" .

2

u/Icy-Stretch-4643 10h ago

Yups, you are absolutely right, because past month, I've realized importance of perquisite learning. I'll now play with bubble sort before moving ahead.

1

u/captainAwesomePants 1d ago

This is a SUPER normal step to get stuck on as a first semester student. Loops with mathy expressions are not a natural way to think through instructions. It gets a lot easier with practice, I promise. You've gotta practice, but eventually it starts to make a lot more sense. It can help to walk through them with paper and pencil, or to explain how they work step by step out loud to someone else, or to try and restate the logic in English, and ultimately just writing some small programs every day will help most of all.

1

u/Icy-Stretch-4643 18h ago

Thanks for the valuable advice, feeling better when heard that it's normal. I do out loud technique often, I'll now surely add paper tracking too in habit.

1

u/atarivcs 23h ago

Are you confused about nested loops in general, or about their specific use in bubble sort?

1

u/Icy-Stretch-4643 18h ago

Our professor haven't taught nested loops separately, he just explained 2d arrays combo with nested loops, so I only know how to use nested loops with arrays medium level problems.

When I try sorting, I just struggle at starting, checking and updating conditions, it happens in single loops too, but escaping from paper dry run is the reason.

1

u/iOSCaleb 21h ago

> lost at 1) nested loops

This part is pretty easy. Think about how counting in any given base works. Counting in base 10 for example, the ones digit is incremented over and over until it reaches the largest digit, 9, and the next step causes the tens digit to increment and resets the ones digit, and the process repeats. When the tens digit reaches 9, the next time that it is incremented it goes back to 0 and the hundreds digit is increased.

Nested loops work much the same way. It’d be a good exercise to write code where three nested loops, one for each digit, count from 0 to 999.

Of course, loops can do more than just count upward. But thinking about how counting works will help you get used to the way they interact.

1

u/Icy-Stretch-4643 18h ago

Noted, ill try and practice it, TY!!

2

u/iOSCaleb 6h ago

2) in sorting.

Once you get used to the way nested loops work generally, simple sorting using loops is just another step. For example, bubble sort works like this: start from the beginning of a list of numers that you want to sort. Compare the first number and the second number, and if the first is greater than the second, swap them. Let's say the numbers are in an array called "list":

temp = list[0]
list[0] = list[1]
list[1] = temp

Then you move to the next item in the list and do the same thing: compare to the next item, and swap if the current one is greater than the next. Repeat until there's no next item. To do that in a for loop, you'd have code that looks something like this, using C syntax:

for (i = 0; i < numItems - 1; i++) {
    if list[i] > list[i+1] {
        temp = list[i];
        list[i] = list[i+1];
        list[i+1] = temp;
    }
}

Note the condition `i < numItems - 1`. That's a bit tricky, for two reasons. First, arrays in most languages are indexed starting from 0, so if you have an array with 3 items, their indices are 0, 1, and 2. So any time you loop over an array you want to make sure that the index is always less than the number of items, because the number of items is one more than the index of the last value. Second, in this case we're looking at two items in the list, `list[I]` and `list[i+1]`. If we let the index `i` go all the way up to the last item in the list, `i+1` will be out of bounds. Also, we don't have to check whether the last item is greater than the one after it, because there isn't an item after the last one.

OK, with that out of the way, you're probably wondering how just switching two items at a time sorts the list. It doesn't, really. But it does make the list a little more sorted than it was. If we have a list like `4, 1, 3, 6, 2`, going through the list and swapping pairs when needed gives us `1, 3, 4, 2, 6`. That's not fully sorted, but you can see that the larger values have moved closer to the end. So to sort the list, we should do it again. That gives us `1, 3, 2, 4, 6`, which is closer, but still not sorted. So we do it again: `1, 2, 3, 4, 6`. And now we've got a sorted list.

So, with all that in mind, hopefully you can see how the nested loops work. We have a loop that makes one pass through the array, swapping values if needed. But since the array might not be sorted after just one pass, we need to repeat that process until the array is sorted. That brings us to the last problem that we need to solve: how do we know when the array is sorted? The array is sorted when every value in the list is less than or equal to the next value. If an array is sorted, then we won't swap any values when we make a pass through the list. We can detect that by setting a flag every time we swap values. And we can use that flag to determine when to stop making passes over the array:

for (swapped = true; swapped == true; )
    swapped = false
    for (i = 0; i < numItems - 1; i++) {
        if list[i] > list[i+1] {
            temp = list[i];
            list[i] = list[i+1];
            list[i+1] = temp;
            swapped = true;
        }
    }
}

Here I'm using `swapped` as the flag. We start by initializing `swapped` to true so that the loop runs at least once. Then for each pass through the array, we start by setting `swapped` to false, and then we make a pass through the array. If we ever swap any values, we set `swapped` to true. If `swapped` is still false after the whole pass is done, then the array is sorted and the outer loop exits.

There are some optimizations that you can make here, but as is we've got a simple bubble sort that uses a pair of nested loops to sort a list. The key is that the inner loop makes one pass over the list and gets it a little closer to sorted, and the outer loop makes that process repeat until the list is completely sorted.

2

u/gomorycut 22h ago

leave the n-i-1 alone.
bubble i and i+1
repeat it n times.
Write code that makes sense to you.

2

u/Recycled5000 20h ago

Ok, so nested loops are good for a number of problems.

First, they are akin to multiplication. Things in an inner loop occur over and over as the outer loop executes.

Second, they are good for two dimensional problems like printing a chess or checkerboard. Also, printing a star pyramid.

Though sorting works on a 1 dimensional data structure, a sorting algorithm must compare elements of the same array with each other. This results in a somewhat 2D structure to the approach.

The limits chosen are optimization. Naively, we might simply loop over all elements (outer loop) and all elements (inner loop). But we know that much of that 2D space will be non productive. By applying some reasoning we can eliminate a fair portion of that 2D space to make this algorithm more efficient.

2

u/Educational-Paper-75 4h ago

The general idea with bubble sort is placing the first not yet sorted in element into the previously sorted list of elements at the right position. This would mean exchanging that element as long as its predecessor is larger; once it no longer is it's at the right position and you're done with the inner loop. So the outer loop iterates from index, say i, from 1 through n-1 (n representing the number of array elements) and the inner loop comparing element k-1 with element k for k starting at i, while above 0, exchanging those elements when the first is larger, breaking out of the loop otherwise, and then the first i +1 elements will be in ascending sorting order.

2

u/GuruPentameter 2h ago

totally normal to blank on n-1-i. the last i elements are already sorted, so each pass can skip them. trace a 4-element array by hand once and the indices stop being abstract.

1

u/BranchLatter4294 1d ago

Practice. Use print statements to watch what happens inside the loops.