选择排序
第一步:从一串无序数字串中选一个最小的与第一个数交换位置
第二步:从剩下的数字中选一个最小的与第二个数交换位置
第三步:从剩下的数字中选一个最小的与第三个数字交换位置
以此类推...
运行结果:
抱歉,上面的排序是从小到大,打字错误
源码如下:
#include<stdio.h> typedef int keytype;//关键字类型 //选择排序 void selectsort(keytype k[] , int n) { int min; for (size_t i = 1; i <= n-1; i++)//剩最后一个元素的时候,这个元素肯定是最大的 { //选出最小的数字 min = i; for (size_t j = i+1; j <= n; j++) { if (k[j] < k[min]) { min = j; } } //交换位置 if(min!=i) { k[0] = k[i]; k[i] = k[min]; k[min] = k[0]; } } } #define MAX 100 int main() { //读取一串数字 printf("请输入一串无序数字:"); int c; int n = 1; keytype k[MAX]; while ((c = getchar())!=' ') { k[n++] = c-'0'; } if (c == ' ') { k[n] = ' '; } //选择排序 selectsort(k , n-1); printf("这串数字从大到小为:"); for (size_t i = 1; i <= n-1; i++) { printf("%d",k[i]); } return 0; }