選擇排序:每趟從待排序的記錄中選出關鍵字最小的記錄,順序放在已排序的記錄序列末尾,直到所有排序結束爲止。php
簡單選擇排序很簡單,它的大體處理流程爲:html
動態效果示意圖:python
舉例說明,處理過程示意圖以下所示:算法
如圖所示,每趟排序中,將當前第 i 小的元素放在位置 i 上。數組
Python:列表排序函數
# -*- coding:utf-8 -*- def SelectSort(input_list): ''' 函數說明:簡單選擇排序(升序) Parameters: input_list - 待排序列表 Returns: sorted_list - 升序排序好的列表 ''' if len(input_list) == 0: return [] sorted_list = input_list length = len(sorted_list) for i in range(length): min_index = i for j in range(i + 1, length): if sorted_list[min_index] > sorted_list[j]: min_index = j if min_index == i: continue temp = sorted_list[i] sorted_list[i] = sorted_list[min_index] sorted_list[min_index] = temp # 上面三步交換也能夠使用交叉賦值 return sorted_list if __name__ == '__main__': input_list = [6, 4, 8, 9, 2, 3, 1] print('排序前:', input_list) sorted_list = SelectSort(input_list) print('排序後:', sorted_list)
C:字符串排序性能
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 20 // 最大字符串長度 /* ---------------------------------------- */ /* 選擇排序法 */ /* ---------------------------------------- */ void select(char *string, int count) { int pos; // 目前最小的字符 int i, j; char temp; for ( i = 0; i < count - 1; i++ ) // 第一層循環 { pos = i; temp = string[pos]; /* 查找最小的字符 */ for ( j = i + 1; j < count; j++ ) // 第二層循環 if ( string[j] < temp ) // 是否更小 { pos = j; // 新的最小字符 temp = string[j]; } string[pos] = string[i]; // 交換兩字符 string[i] = temp; printf("輸出結果: [%s]\n", string); // 輸出交換後字符串 } } /* ---------------------------------------- */ /* 主程序: 輸入字符串後將字符串排序 */ /* ---------------------------------------- */ int main(void) { char string[MAX]; // 字符串數組 int count; // 字符串長度 printf("輸入要排序的字符串 ==> "); gets(string); // 讀取字符串 count = strlen(string); // 計算字符串長度 select(string, count); // 選擇排序法 printf("\n輸出排序結果: [%s]\n",string); // 輸出排序後字符串 }
簡單選擇排序的比較次數與序列的初始排序無關。假設待排序的序列有 N 個元素,則比較次數老是 N (N-1)/ 2
。ui
而移動次數與序列的初始排序有關。當序列正序時,移動次數最少,爲 0 。url
當序列反序時,移動次數最多,爲 3N (N - 1) / 2
。code
因此,綜合以上,簡單排序的時間複雜度爲 O(N2)。
簡單選擇排序須要佔用 1 個臨時空間,用於保存最小值得索引。
本站整理自: