C 选择排序算法

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 100
void selectSort(char *arr, int total){

    int i,j,pos;
    char temp;
    for(i=0;i<total-1;i++){
        pos = i;             //此处需注意每次排序是一定要给pos 赋值 否则当不交换变量时会有BUG
        temp = arr[pos];
        for(j=i+1;j<total;j++){
            if(arr[j] < temp){
               temp = arr[j];
               pos = j;
            }
        }
        arr[pos] = arr[i];
        arr[i] = temp;
        printf("排序后的数组为%s \n",arr);
    }

}
void main(){
   
    char a[MAX]; 
    printf("请输入要排序的字符串");
    gets(a);
    selectSort(a,strlen(a));
}
 

 

结果:

请输入要排序的字符串54321
排序后的数组为14325
排序后的数组为12345
排序后的数组为12345
排序后的数组为12345
请按任意键继续. . .

posted @ 2012-09-26 00:36  ﹏Sakura  阅读(245)  评论(0编辑  收藏  举报