求解,求大神帮我
4. 编写一个完整程序,将键盘输入的任意长度的字符串中的字符从小到大排序。具体要求
如下:
(1)字符串排序功能用一个函数实现;
(2) 在主函数中定义一个足够长的字符数组 (50 个字符长度),然后从键盘输入一行字
符存入该数组,再调用字符串排序西数对字符串中的字符排序。
(3) 在主函数中输入排序后的字符串。
两种方法,都使用快速排序:一种是利用C库函数qsort,另外一种是使用自定义快速排序。
方法一:使用qsort
#include <stdio.h> /* printf */
#include <stdlib.h> /* qsort */
#include <iostream>
using namespace std;
int compare(const void* a, const void* b)
{
return *(char*)a - *(char*)b;
}
void sortCharArray(char *p)
{
if (!p) return;
qsort(p, strlen(p), sizeof(p[0]), compare);
}
int main()
{
char a[51];
fgets(a, sizeof(a), stdin); // 读取一行字符串
sortCharArray(a);
cout << a << endl;
return 0;
}
方法二:自定义快速排序
int cmp(char c1, char c2)
{
return c1 - c2;
}
int Partition(char a[], int low, int high)
{
char pivotKey = a[low]; // 假定当前枢轴为low对应元素
while (low < high)
{
while (low < high && cmp(pivotKey, a[high]) <= 0) high--;
a[low] = a[high];
while (low < high && cmp(pivotKey, a[low]) >= 0) low++;
a[high] = a[low];
}
a[low] = pivotKey;
return low;
}
// 对a[low..high]进行快速排序
void q_sort(char a[], int low, int high)
{
int pivotLoc = Partition(a, low, high); // 一次划分求出枢轴位置
if (pivotLoc > low) {
q_sort(a, low, pivotLoc - 1);
}
if (pivotLoc < high) {
q_sort(a, pivotLoc + 1, high);
}
}
// 对a[0..n-1]进行快速排序
void myquick_sort(char a[], int n)
{
q_sort(a, 0, n - 1);
}
// main函数中调用
...
myquick_sort(a, strlen(a));
...