# 1. 选择排序

一句话总结：

> n^2遍历，每遍历一轮选择一个最小/大值，
>
> 然后与当前位替换，最终得到排序结果

python

```python
class Sort:
    def sort(self):
        pass

    def less(self, a, b):
        return a < b

    def swap(self, nums, i, j):
        nums[i], nums[j] = nums[j], nums[i]


class Selection(Sort):
    def sort(self, nums):
        n = len(nums)
        for i in range(n):
            min = i
            for j in range(i + 1, n):# 第二轮每次选择出后面元素中最小的，并记录最小位置
                if self.less(nums[j], nums[min]):
                    min = j
            self.swap(nums, i, min) #结束选择后，直接最小位置和i号互换


if __name__ == '__main__':
    arr = [5, 1, 8, 7, 10, 6, 9, 5, 20, 3, 0]
    print(arr)
    sort = Selection()
    sort.sort(arr)
    print(arr)
```

java

```java
package sort;

public abstract class Sort<T extends Comparable<T>> {
    public abstract void sort(T[] nums);

    public boolean less(T v,T w){
        return v.compareTo(w)<0;
    }

    public void swap(T[] a,int i,int j){
        T t=a[i];
        a[i]=a[j];
        a[j]=t;
    }
}


public class Selection<T extends Comparable<T>> extends Sort<T>{
    @Override
    public void sort(T[] nums) {
        int n=nums.length;
        for(int i=0;i<n;i++){
            int min=i;
            for(int j=i+1;j<n;j++){
                if(less(nums[j],nums[min])) min=j;
            }
            swap(nums,i,min);
        }
    }

    public static void main(String[] args){
        Integer[] arr={
                5,1,8,7,10,6,9,5,20,3,0
        };
        Sort<Integer> sort=new Selection<>();
        sort.sort(arr);
        ArrayUtils.printArray(arr);
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://im-qianuxn.gitbook.io/pytorch/ji-suan-ji/shua-ti/pai-xu-lei/1xuan-ze-pai-xu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
