题目描述
给定n个字符串,请对n个字符串按照字典序排列。
输入描述:
输入第一行为一个正整数n(1≤n≤1000),下面n行为n个字符串(字符串长度≤100),字符串中只含有大小写字母。
输出描述:
数据输出n行,输出结果为按照字典序排列的字符串。
解法1(C语言):
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int Partition(char *A[], int low, int high)
{
char *pivot = (char *)malloc(100 * sizeof(char));
pivot = A[low];
while(low < high)
{
while(low < high && strcmp(A[high],pivot) >= 0)
--high;
A[low] = A[high];
while(low < high && strcmp(A[low],pivot) <= 0)
++low;
A[high] = A[low];
}
A[low] = pivot;
return low;
}
void QuickSort(char *A[], int low, int high)
{
if(low < high)
{
int pivotpos = Partition(A, low, high);
QuickSort(A, low, pivotpos - 1);
QuickSort(A, pivotpos + 1, high);
}
}
int main()
{
int n, i;
char *str[1000];
scanf("%d", &n);
for(i = 0; i < n; ++i)
{
str[i] = (char*) malloc(100*sizeof(char));
scanf("%s", str[i]);
}
QuickSort(str, 0, n - 1);
for(i = 0; i < n; ++i)
printf("%s\n", str[i]);
return 0;
}
解法2(Python):
n = int(input())
lst = []
for i in range(n):
s = input()
lst.append(s)
lst.sort()
for i in range(n):
print(lst[i])
原文地址:https://blog.51cto.com/13614527/2468775
时间: 2024-10-19 07:13:15