[C] PTA final grade sorting (merge sort)

Exam is over, the whole class scores are out. The teacher needs to do a sort of score, take a look at the arrangement from high to low, the score is like.

Input formats:

A first line is n, the number of students in the class, 1 <= n <= 500000. The second line there are n points, 0 <= Score <= 100, scores are integers, no 0:05.

Output formats:

Score outputting sorted in descending order according to the same score row together, the interval between each of the two fractions a space.

Sample input:

10
0 60 73 60 82 90 100 18 55 84 

Sample output:

100 90 84 82 73 60 60 55 18 0

 Ideas:

The main sorting algorithm is selected, taking into account the time complexity of the algorithm. Select a sorting method using the start, but with a final embodiment calculates the overtime, after the switch merge sort method, test passed.

C language:

#include<stdio.h>
#include<stdlib.h>

void mergeSort(int a[], int len, int start, int end);
void merge(int a[], int len, int start, int mid, int end);

int main(){
    int n;
    scanf("%d",&n);
    int scores[n];
    for(int i=0; i<n; i++){
        scanf("%d",&scores[i]);
    }
    
	mergeSort(scores, n, 0, n-1);

    for(int i=0; i<n; i++){
        printf("%d",scores[i]);
        if(i<n-1){
            printf(" ");
        }
    }
    return 0;
}

void mergeSort(int a[], int len, int start, int end){
	if(start >= end) return;
	int mid = (start + end)/2;
	mergeSort(a, mid-start+1, start, mid);
	mergeSort(a, end-mid, mid+1, end);
	
	merge(a, len, start, mid, end);
	
}

void merge(int a[], int len, int start, int mid, int end){
	int* temp = (int*)malloc(len*sizeof(int));
	int i, j, k = 0;
	i = start;
	j = mid+1;
	while(i<=mid && j<=end){
		temp[k++] = a[i] > a[j] ? a[i++] : a[j++];
	}
	while(i<=mid){
		temp[k++] = a[i++];
	}
	while(j<=end){
		temp[k++] = a[j++];
	}
	
	for(int m = 0; m < k; m++){
		a[start + m] = temp[m];
	}
	
	free(temp);
}

References:

Five merge sort of vernacular classical algorithm to achieve series

C sorting algorithm

Published 37 original articles · won praise 47 · Views 100,000 +

Guess you like

Origin blog.csdn.net/u013378642/article/details/104978134