Implementing the Selection Sort Algorithm with Python
Selection sort is a simple and intuitive sorting algorithm. Its core idea is to repeatedly select the smallest (or largest) element from the unsorted elements and place it at the end of the sorted portion until the entire array is sorted. The steps are as follows: initially, assume the current element is the smallest, traverse the unsorted portion to find a smaller element, swap it to the end of the sorted portion, and repeat until completion. In Python implementation, the outer loop variable `i` controls the end of the sorted portion (ranging from 0 to n-2). The inner loop variable `j` traverses the unsorted portion (from i+1 to n-1) to find the position `min_index` of the smallest element. Finally, swap `arr[i]` with `arr[min_index]`. For the test array [64, 25, 12, 22, 11], the sorted result is [11, 12, 22, 25, 64]. It has a time complexity of O(n²), a space complexity of O(1), and is an in-place sorting algorithm. Its characteristics are: simple to understand, but unstable (the order of identical elements may be swapped), and suitable for small-scale data.
Read MoreImplementing the Selection Sort Algorithm in Java
Selection sort is a simple and intuitive sorting algorithm. Its core idea is to repeatedly select the smallest (or largest) element from the unsorted portion and place it at the end of the sorted portion until the entire array is sorted. The basic approach involves an outer loop to determine the end position of the sorted portion, and an inner loop to find the minimum value in the unsorted portion, followed by swapping this minimum value with the element at the current position of the outer loop. In Java implementation, the `selectionSort` method is implemented with two nested loops: the outer loop iterates through the array (with `i` ranging from 0 to `n-2`), and the inner loop (with `j` ranging from `i+1` to `n-1`) finds the index `minIndex` of the minimum value in the unsorted portion. Finally, the element at position `i` is swapped with the element at `minIndex`. Taking the array `{64, 25, 12, 22, 11}` as an example, the sorted array `[11, 12, 22, 25, 64]` is gradually constructed through each round of swaps. The time complexity is O(n²), making it suitable for small-scale data. This algorithm has a simple logic and easy-to-implement code, serving as a typical example for understanding the basic sorting concepts.
Read More