Chinaunix首页 | 论坛 | 博客
  • 博客访问: 984443
  • 博文数量: 150
  • 博客积分: 3017
  • 博客等级: 少校
  • 技术积分: 3829
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-19 14:40
个人简介

Now in Baidu WISE team

文章分类

全部博文(150)

文章存档

2014年(8)

2013年(31)

2012年(111)

分类: C/C++

2012-12-27 23:23:25

对字符串进行排序,在排序中,字符串 “bc”,“ad”,“ac”,“hello”,“xman”,“little”,“during”,“day”能够排序成 “ad”,"ac",“bc”,“during”,“day”,“hello”,“little”,
 
解法:
排序类问题无论任何变化,不管是排字符串还是按某种规则排序,本质都是一样,所变化的无非是元素的比较方式。
对于该题目同样适用。
使用快排,对于两个串,根据规则进行大小比较。
 
需要注意字符串交换位置的方法。
codepad.org已验证。

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>

  4. void swap(char **str1,char **str2){
  5.         char *temp=*str1;
  6.         *str1=*str2;
  7.         *str2=temp;
  8. }
  9. int compare(char* str1, char*str2){
  10.         while(*str1 && *str2 && *str1==*str2){
  11.               str1++;
  12.               str2++;
  13.         }
  14.     return *str1-*str2;

  15. }

  16. int partition(char** set, int startindex, int endindex){
  17.     if(set == NULL) return ;
  18.     char* pi = set[endindex];
  19.     int low = startindex;
  20.     int high = startindex+1;
  21.     for(;high<endindex;high++){
  22.         if(compare(set[high], pi) < 0){
  23.             low++;
  24.             swap(&set[low],&set[high]);
  25.         }
  26.     }
  27.     low++;
  28.     swap(&set[low], &set[high]);
  29.     return low;
  30. }

  31. void sort(char** set, int startindex, int endindex){
  32.     if(startindex>= endindex) return;
  33.     int mid = partition(set, startindex, endindex);
  34.     sort(set, startindex, mid-1);
  35.     sort(set, mid+1, endindex);
  36. }


  37. int main(){
  38.     char *set[] = {"a","ac","ab","aeg","aef"};
  39.         int i = 0;
  40.     sort(set, 0,4);
  41.     for(;i<5;i++){
  42.         printf("%s ", set[i]);
  43.     }
  44.         printf("\n");
  45. }

阅读(15454) | 评论(0) | 转发(2) |
给主人留下些什么吧!~~