C language: faster row, heap row, counting time in three different sorting algorithm 100 million numbers

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

#define N 100000000 // number of one hundred million sorted
#define M 100000

#define SWAP(a,b) {int temp;temp= a; a=b;b=temp;}

void arrPrint(int *arr)
{
int i;
for (i = 0; i < N; i++)
{
printf("%6d", arr[i]);
}
printf("\n");
}
//
int partition(int *arr,int left,int right) {
int i, j;
for (i = left, j = left; i < right; i++) {
if (arr[i] < arr[right]) {
SWAP(arr[i], arr[j]);
j++;
}
}
SWAP(arr[right], arr[j]);
return j;
}
void arrQuickSort(int *arr, int left, int right) {
int pivot;//英 [pivet] 中点
if (left < right) {
pivot = partition(arr, left, right);
arrQuickSort(arr, left, pivot - 1);
arrQuickSort(arr, pivot + 1, right);
}
}
// heapsort
int changeToMaxHeap (int ARR [], int adjustPOS, int arrLen) {
int DAD = adjustPOS;
int Son = 2 * DAD +. 1;
the while (Son <arrLen) {
IF (Son +. 1 <arrLen && ARR [Son ] <ARR [Son +. 1]) {// Son +. 1 <arrLen
Son ++;
}
IF (ARR [Son]> ARR [DAD]) {
the SWAP (ARR [Son], ARR [DAD]);
DAD = Son;
= 2 * + DAD Son. 1;
}
the else {
BREAK;
}
}
}
void arrHeapSort (int * ARR) {
int I;
for (I = N / 2; I> = 0; I-) {// the outer loop dad into a different node
changeToMaxHeap (arr, i, N) ; // changeToMaxHeap () is responsible for adjusting only a single stack of large root, a function can be placed inside the package good
}
the SWAP (ARR [0], ARR [N-. 1]) ;
for (i = N-1; i > 1; i++)
{
changeToMaxHeap(arr,0, i);
SWAP(arr[0], arr[i-1]);
}
}
//count sort
int arrCountSort(int *arr) {
int count[M];
for (int i = 0; i < N; i++)
{
count[arr[i]]++;
}
int i, j, k=0;
for (i = 0; i < M; i++) {//i是数据范围,控制数的范围大小
for (j = 0; j < arr[i]; j++) {
arr[k++] = i;
}
}
}
int main() {
int i;
//int arr[N];
int *arr = (int *)malloc(N * sizeof(int));

time_t startQuick, endQuick;
time_t startHeap, endHeap;
time_t startCount, endCount;

srand(time(NULL));
for (i = 0; i < N; i++) {
	arr[i] = rand()%M;
}
//arrPrint(arr);

//startQuick = time(NULL);
//arrQuickSort(arr, 0, N - 1);
//endQuick = time(NULL);
//arrPrint(arr);
//printf("quick sort use time=%d s\n", endQuick - startQuick);

startHeap = time(NULL);
arrQuickSort(arr, 0, N - 1);
endHeap = time(NULL);
//arrPrint(arr);
printf("heap sort use time=%d s\n", startHeap - endHeap);

//startCount = time(NULL);
//arrCountSort(arr);
//endCount = time(NULL);
//arrPrint(arr);
//printf("count sort use time=%d s\n", startCount - endCount);
system("pause");

}

Released three original articles · won praise 0 · Views 200

Guess you like

Origin blog.csdn.net/Charlie_Lee_CS/article/details/104422102
Row