【问题标题】:quicksort algorithm to sort words in C快速排序算法对C中的单词进行排序
【发布时间】:2013-07-24 11:24:39
【问题描述】:

在我的在线课程的一个作业中,我必须使用快速排序算法对单词列表进行排序。我能够对数字列表进行排序,但不能对单词进行排序。函数 IthChar 接受 2 个参数,一个字符串和一个表示字符串索引的整数,并返回位于索引位置的字符。
例如 IthChar("Paul", 0) --> P

这里是快速排序、交换和 swapPivot 函数:

void quickSort(string array[], int left, int right)
{
      int I, J, pivot;
      char chI, chJ, chPivot;

      if(left<right)
      {
                    pivot=left;
                    I=left;
                    J=right;
                    while(I<J)
                    {
                               chI=IthChar(array[I], 0);
                               chJ=IthChar(array[J], 0);
                               chPivot=IthChar(array[I], 0);
                               while(chI<=chPivot&&I<right)
                               I++;
                               while(chJ>chPivot)
                               J--;
                               if(I<=J)
                               {
                                       swap(array, I, J);
                               }
                    }   
                    swapPivot(array, pivot, J);
                    quickSort(array, left, J-1);
                    quickSort(array, J+1, right); 
      }
}

void swap(string array[], int loc, int loc1) 
{
          int temp;

          temp=array[loc];
          array[loc]=array[loc1];
          array[loc1]=temp;
}     

void swapPivot(string array[], int pivot, int J)
{
          int temp;

          temp=array[pivot];
          array[pivot]=array[J];
          array[J]=temp;
}

谢谢:D

【问题讨论】:

  • 你确定它是 C 而不是 C++?问题是什么?此处唯一的问号在此评论中。
  • 另外,请注意temp 被声明为int,但您稍后将string 分配给它:int temp; temp=array[pivot];
  • 你应该直接写std::sort(strVector.begin(), strVector.end());...
  • 是的,它在 c 中,问题是为什么它什么都不打印

标签: c arrays string char quicksort


【解决方案1】:

你应该编写(或者如果你已经有的话重用)一个字符串比较函数。

【讨论】:

  • 或使用strcmp from &lt;string.h&gt;
  • @AdrianJandl 这就是我的想法,但由于奇怪的IthChar OP 正在重新实现字符串,我有这样的印象。
  • 考虑到他将它们分配给普通的char,我假设IthChar 是一个不遵循命名约定的函数。
猜你喜欢
  • 2018-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-07
  • 1970-01-01
  • 1970-01-01
  • 2021-12-15
相关资源
最近更新 更多