1、选择排序的思路是:遍历数组,第一遍找出所有成员的最小值,放到数组下标为0的位置,第二遍从剩余内容中,再次找出最小值,放到数组下标为1的位置,以此类推,遍历完成所有的数组内容,最后结果就是:数组是按照从小到大顺序进行排序的。
2、按照C语言、java、python的顺序,分别实现如下,在对应编译平台上都是编译通过的:
C语言版本:
#include <stdio.h> int main() { int i; int j; int temp; int origin[] = {2,1,4,3,5}; int length = sizeof(origin)/sizeof(origin[0]); for(i = 0; i < length; i++) { for(j = i; j < length; j++) { if( origin[j] < origin[i] ) { temp = origin[i]; origin[i] = origin[j]; origin[j] = temp; } } } for(i =0; i < length; i++) { printf("%d ", origin[i]); } return 0; }
java版本:
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package selectsort; /** * * @author zhou */ public class SelectSort { /** * @param args the command line arguments */ public static void main(String[] args) { int i; int j; int temp; int origin[] = {2,1,4,3,5}; int length = origin.length; for(i = 0; i < length; i++) { for(j = i; j < length; j++) { if( origin[j] < origin[i] ) { temp = origin[i]; origin[i] = origin[j]; origin[j] = temp; } } } for(i =0; i < length; i++) { System.out.println(origin[i]); } } }
python版本
def main(): origin = [2, 1, 4, 3, 5] length = len(origin) for i in range(0, length): for j in range(i, length): if origin[j] < origin[i]: temp = origin[i] origin[i] = origin[j] origin[j] = temp for i in origin: print(i) if __name__ == '__main__': main()