我实现的Snippet-1是冒泡排序的另一种写法还是其他排序算法?
Hey there! Great question—mixing up sorting algorithms is super common when you're first learning them, so don't feel bad about this. Let's break down the key differences between selection sort and bubble sort first, then we can pin down what your snippet-1 is doing.
First, let's recap the core identities of each algorithm:
- Selection Sort: The whole point is to hunt down the minimum (or maximum) value in the unsorted portion of the array, then swap it with the first element of that unsorted section. You only do one swap per pass through the array, building up the sorted section one element at a time.
- Bubble Sort: This one relies on adjacent element swaps. You iterate through the unsorted section, comparing each pair of neighboring elements and swapping them if they're out of order. Each pass "bubbles" the largest (or smallest) unsorted element into its correct position, and you'll do multiple swaps per pass.
Now, based on what you described—your snippet-1 didn't implement the "find the minimum and swap once" core of selection sort—it's almost certainly a variant of bubble sort.
Here's why: If your code was looping through the array and swapping adjacent elements whenever they were in the wrong order (even if the loop structure looked a little different from the standard bubble sort you learned), that's still bubble sort at heart. Bubble sort has a few minor variations (like sorting from the end forward instead of the start, or stopping early if no swaps happen in a pass), but all of them share that core adjacent-swap behavior.
To confirm, think about this quick litmus test: Did your snippet-1 make multiple swaps in each iteration through the array? If yes, that's bubble sort. If it only made one swap per iteration (after finding the min), that would be selection sort.
Since you said snippet-1 missed selection sort's key feature, it's safe to say it's either standard bubble sort or a small variation of it—definitely not selection sort, and not a new/uncommon algorithm.
内容的提问来源于stack exchange,提问作者user3511777

