Java
/**
* @author LiuZhiguo
* @date 2019/10/1 16:31
*/
public class SelectSort {
public static void selectSort(int[] arr, int n) {
int i, j, mini;
int temp;
for (i=0;i<n;i++) {
mini =i;
for (j=i+1;j<n;j++) {
if (arr[mini] > arr[j])
mini = j; //mini记录当前比较过程中最小值的下标
}
temp = arr[i];
arr[i] = arr[mini];
arr[mini] =temp;
}
}
public static void main(String[] args) {
//SelectSort selectSort = new SelectSort();
int[]arr = {2,5,1,10,4,7,12,13,6,11,21,18,12};
selectSort(arr, arr.length);
for (int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
}
Python
class SelectSort:
def selectSort(self, nums):
n = len(nums)
for i in range(0, n):
min = i # min作为当前最小值的下标
for j in range(i+1, n): #在后面选择出最小的值的下标作为min
if nums[j] < nums[min]:
min = j
if i != min:
temp = nums[i]
nums[i] = nums[min] #把这一趟选择出来的最小值放到无序序列的最前面
nums[min] = temp
if __name__ == '__main__':
test = SelectSort()
nums = [20, 12, 8, 16, 22, 19, 25, 6, 32, 14]
test.selectSort(nums)
print(nums)
结果:
E:\Anaconda3\python.exe D:/program/src/main/Python/SelectSort.py
[6, 8, 12, 14, 16, 19, 20, 22, 25, 32]