選擇排序

選擇排序的思想比較簡單將數組中最大的數與數組的最後一個數交換位置,然後再將數組截去最後一個數,再次將新數組中的最大數與新數組的最後一個數交換位置。一直循環下去,直到數組的長度爲1
在這裏插入圖片描述

下面是插入排序的c語言

#include <stdio.h>

int findMaxPos(int arr[],int n){
        int max = arr[0];
        int pos = 0;
        int i;
        for (i=0; i<n; i++){
        if (arr[i] > max){
                max = arr[i];
                pos = i;
                }
        }
        return pos;
}

void selectionSort(int arr[], int n){
        int i;
        while (n > 1){
                int pos = findMaxPos(arr,n);
                int temp = arr[pos];
                arr[pos] = arr[n-1];
                arr[n-1] = temp;
                n--;
        }
}

int main(){
        int arr[] = {5,8,9,7,6,1,2,4,3};
        selectionSort(arr,9);
        int i;
        for (i=0;i<9;i++){
                printf("%d\n",arr[i]);
        }
        return 0;
}

隨手也寫了一個python的實現

def findMaxPos(nums):
    return nums.index(max(nums))

def selection_sort(nums):
    len_nums = len(nums)
    while len_nums > 1:
        pos = findMaxPos(nums[:len_nums-1])
        nums[len_nums-1],nums[pos] = nums[pos],nums[len_nums-1]
        len_nums -= 1

if __name__ == "__main__":
    nums = [4,2,6,5,3]
    selection_sort(nums)
    print(nums)
        
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章