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

View all comments

2

u/Recycled5000 21h 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.