【十二题解】 | #输入整型数组和排序标识,对其元素按照升序或降序进行排序#(归并排序)
输入整型数组和排序标识,对其元素按照升序或降序进行排序
http://www.nowcoder.com/practice/dd0c6b26c9e541f5b935047ff4156309
好久没用过归并了,练一下
#include<stdio.h>
void merge(int* a, int *tmp, int l, int r, int rightend){
int lefend = r - 1;
int lenth = rightend - l + 1;
int loc = l;
while(l<=lefend && r <=rightend){
if(a[l]<a[r]){
tmp[loc++] = a[l++];
}
else{
tmp[loc++] = a[r++];
}
}
while(l<=lefend){
tmp[loc++]=a[l++];
}
while(r<=rightend){
tmp[loc++]=a[r++];
}
while(rightend >= 0){
a[rightend--]=tmp[rightend];
}
}
void mort(int* a, int* tmp, int l, int rightend){
int center;
if(l < rightend){
center = (rightend+l)/2;
mort(a, tmp, l, center);
mort(a, tmp, center+1, rightend);
merge(a, tmp, l, center+1, rightend);
}
}
void mort_sort(int* a, int n){
int *tmp=(int*)malloc(sizeof(int)*n);
mort(a, tmp, 0, n-1);
}
int main(){
int number;
int data[1000]={0};
int sign;
while(scanf("%d", &number) != EOF){
for(int i=0; i<number; i++){
scanf("%d", &data[i]);
}
scanf("%d", &sign);
mort_sort(data, number);
if(sign){
for(int i=number-1; i>=0; i--){
printf("%d ", data[i]);
}
}
else{
for(int i=0; i<number; i++){
printf("%d ", data[i]);
}
}
printf("\n");
}
}