题解 | #归并排序#
归并排序
http://www.nowcoder.com/practice/23ed40416d9c4c72816edb12daa3bdff
C的解法:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
int num;
char k;
char l;
}List;
int CleanStr(char str[]){
int i,len=strlen(str);
for(i=0;i<len;i++){
str[i]='\0';
}
return 1;
}
int main()
{
char str[10000]={'\0'};
while(fgets(str,10000,stdin)!=NULL){
char *p=strchr(str,'\n');
*p='\0';
int i,j,k=0,len=strlen(str),numlist[10000],h=0,flag=0;
char temp[100]={'\0'};
for(i=0;i<len;){
if(str[i]>='0'&&str[i]<='9'||str[i]=='-'){
if(str[i]=='-'){
flag=1;
i++;
}
while(str[i]>='0'&&str[i]<='9'){
temp[k++]=str[i];
i++;
}
k=0;
if(flag==1){
numlist[h++]=0-atoi(temp);
flag=0;
}
else{
numlist[h++]=atoi(temp);
}
CleanStr(temp);
}
else{
i++;
}
}
for(i=0;i<h;i++){
for(j=0;j<h-i-1;j++){
if(numlist[j]>numlist[j+1]){
k=numlist[j];
numlist[j]=numlist[j+1];
numlist[j+1]=k;
}
}
}
CleanStr(str);
printf("[%d, ",numlist[0]);
for(i=1;i<h-1;i++){
printf("%d, ",numlist[i]);
}
printf("%d]\n",numlist[h-1]);
}
}
#include <stdlib.h>
#include <string.h>
typedef struct{
int num;
char k;
char l;
}List;
int CleanStr(char str[]){
int i,len=strlen(str);
for(i=0;i<len;i++){
str[i]='\0';
}
return 1;
}
int main()
{
char str[10000]={'\0'};
while(fgets(str,10000,stdin)!=NULL){
char *p=strchr(str,'\n');
*p='\0';
int i,j,k=0,len=strlen(str),numlist[10000],h=0,flag=0;
char temp[100]={'\0'};
for(i=0;i<len;){
if(str[i]>='0'&&str[i]<='9'||str[i]=='-'){
if(str[i]=='-'){
flag=1;
i++;
}
while(str[i]>='0'&&str[i]<='9'){
temp[k++]=str[i];
i++;
}
k=0;
if(flag==1){
numlist[h++]=0-atoi(temp);
flag=0;
}
else{
numlist[h++]=atoi(temp);
}
CleanStr(temp);
}
else{
i++;
}
}
for(i=0;i<h;i++){
for(j=0;j<h-i-1;j++){
if(numlist[j]>numlist[j+1]){
k=numlist[j];
numlist[j]=numlist[j+1];
numlist[j+1]=k;
}
}
}
CleanStr(str);
printf("[%d, ",numlist[0]);
for(i=1;i<h-1;i++){
printf("%d, ",numlist[i]);
}
printf("%d]\n",numlist[h-1]);
}
}