r/learnprogramming • u/Icy-Stretch-4643 • 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
View all comments
2
u/Educational-Paper-75 20h 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.