zoukankan      html  css  js  c++  java
  • C语言利用指针排序与选择排序算法

     1 //读入字符串,并排序字符串
     2 #include <stdio.h>
     3 #include <string.h>
     4 #define SIZE 81
     5 #define LIM 20
     6 #define HALT ""
     7 
     8 void stsrt(char * strings [], int num); //字符串排序函数
     9 char * s_gets(char * st,int n);
    10 
    11 int main(void)
    12 {
    13     char input[LIM][SIZE];
    14     char *ptstr[LIM];
    15     int ct =0;
    16     int k;
    17 
    18     printf("Input up to %d lines,and I will sort them.
    ",LIM);
    19     printf("To stop,press the Enter key at a line's start.
    ");
    20 
    21     while(ct<LIM && s_gets(input[ct],SIZE)!= NULL && input[ct][0]!='')
    22     {
    23         ptstr[ct] = input[ct]; //设置指针指向字符串
    24         ct++;
    25     }
    26     stsrt(ptstr,ct); //字符串排序函数
    27     puts("
    Here's the sorted list:
    ");
    28     for (k=0;k<ct;k++)
    29         puts(ptstr[k]);
    30     return 0;
    31 }
    32 
    33 void stsrt(char *strings [], int num)
    34 {
    35     char *temp;
    36     int top,seek;
    37 
    38     for(top=0;top <num -1;top++)
    39         for(seek=top+1;seek<num;seek++)
    40             if(strcmp(strings[top],strings[seek])>0)
    41             {
    42                 temp = strings[top];
    43                 strings[top] = strings[seek];
    44                 strings[seek] = temp;
    45             }
    46 }
    47 
    48 
    49 
    50 char * s_gets(char * st, int n)
    51 {
    52     char * ret_val;
    53     int i=0;
    54 
    55     ret_val = fgets(st, n, stdin); //读取成功,返回一个指针,指向输入字符串的首字符;
    56     if(ret_val)
    57     {
    58         while(st[i]!='
    ' && st[i]!='')
    59             i++;
    60         if(st[i] =='
    ') //fgets会把换行符也吃进来了,fgets会在末尾自动加上;
    61             st[i]='';
    62         else   //其实是''
    63             while(getchar() != '
    ')  //会把缓冲区后续的字符都清空
    64                 continue;
    65     }
    66     return ret_val;
    67 }

    程序解读:

    这个程序的好处是利用字符串指针数组ptstr进行排序,并未改变input,这样也保留了input数组中的原始顺序。这样的做法比直接用strcpy()交换两个input字符串要简单得多。

    程序中还出现了,选择排序算法:(selection sort algorithm):其实就是以strcmp函数为基础来冒泡排序指针

    C库中有更高级的排序函数:qsort(),该函数使用一个指向函数的指针进行排序比较。

  • 相关阅读:
    查看Linux系统版本和内核信息
    XManager连接CentOS6.5
    Linux系统中Ant的安装与实例应用
    Linux常用命令列表
    虚拟机中CentOS系统添加新磁盘
    Linux-IP网络设置
    [原创]Toolbar setNavigationIcon无效
    [转]JAVA回调机制(CallBack)详解
    [原创]PM2使nodejs应用随系统启动
    [原创]Linux(CentOS)下安装mongodb
  • 原文地址:https://www.cnblogs.com/grooovvve/p/9938394.html
Copyright © 2011-2022 走看看