題目描述
給定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])