this post was submitted on 01 Sep 2026
92 points (100.0% liked)
Programmer Humor
33288 readers
1018 users here now
Welcome to Programmer Humor!
This is a place where you can post jokes, memes, humor, etc. related to programming!
For sharing awful code theres also Programming Horror.
Rules
- Keep content in english
- No advertisements
- Posts must be related to programming or programmer topics
- If the mod doesn't find it funny, you're banned. Ha-ha!... For real: do not use the community for "statements". There are other places for such content. Keep it chill and funny.
founded 3 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
Seems straightforward enough. For j values of 1 to i it will not do anything because the largest element in the array has already been moved to position i in some earlier iteration in the i loop. For j values greater than i it then proceeds to find the largest remaining element place in position i.
Edit: I'm leaving my incorrect thought above as is for posterity. As pointed out when j is less than i it does of course swap again resulting in a more difficult (for me) visualization of what the end result looks like. Time to have some fun with it (could read about it, but programming is more fun and I like to experiment).
For the
j > icase I think you're right, it sorts largest to smallest (or, backwards), but for thej < icase it grabs larger values from[0, i]that it initially moved to the top of the array and slots them back in, effectively (if roundabout-ly) correcting the backwards sorting of thej > ipart of the algorithm. Sort of a "two wrongs that accidentally make a right" maneuver.not exactly (if i understand it correctly). the first swap of a pair, where
i < j, basically does not matter, since the same pair will be revisited one more time later with switched values (i = 8, j = 9does not matter.i = 9, j = 8does) and that is when the actual sorting happens. that is why the condition isif a[i] < a[j] then swap, which may seem countreintuitive, but we are comparing the values in the reversed order compared to most of the sorting algorithms.the
i < jpart can be seen as the part that is handled in bubble sort by making the inner loop progressively smaller as the array is partially sorted (not the same elements, but the same amount of work, sort of). it is just ignored here, which is obviously bad for any kind of efficiency, but it allows for that super simple code.