1.准备工作
我们先写一堆工具,后续要用,不然这些写在代码里可读性巨差
#pragma once
#include<stdio.h>//为C语言定义bool类型
typedef int bool;
#define false 0
#define true 1//用于交互a和b
inline void swap(int* a, int* b)
{/*int c = *a;*a = *b;*b = c;*/*a ^= *b;*b ^= *a;*a ^= *b;
}
//在ab之中取最小值
inline int min(int a, int b)
{return a < b ? a : b;
}
//在ab之中取最大值
inline int max(int a, int b)
{return a < b ? b : a;
}//检查越界异常,在编写排序算法时,容易出现下标越界,以此作为检查手段
inline int inRange(int x, int min, int max)
{int res = x >= min && x <= max;if (!res) printf("越界:%d 界限:[%d,%d]\n", x, min, max);return res;
}
//用于int的高效指数计算
inline int intpow(int a, int b)
{int r = 1;for (int i = 0; i < b; i++) r *= a;return r;
}//取得一个数在十进制下的位数
inline int getbitCount(int c)
{int bc = 0;do{bc++;} while (c = c / 10);return bc;
}//获取x的第c位
inline int getbit(int x, int c)
{// v = (x % 100) / 10^c-1return (x % intpow(10, c)) / intpow(10, c - 1);
}
测试函数
我们在sort函数里给出排序算法的实现
#define _CRT_SECURE_NO_WARNINGS#include<stdio.h>
#include<time.h>
#include<malloc.h>
#include<string.h>
#include "sort.h"//检查数组有序性
bool checkArraySort(int* nums, int numsSize, bool* upper)
{int resultA = true;for (int i = 0; i < numsSize - 1; i++){if (nums[i] > nums[i + 1]){//printf("无序数对下标:[%d,%d]\n", i, i + 1);resultA = false;}}if (resultA){*upper = true;return resultA;}int resultB = true;for (int i = 0; i < numsSize - 1; i++){if (nums[i] < nums[i + 1]){resultB = false;}}if (resultB){*upper = false;return resultB;}return false;
}
//输出数组元素
void printElements(int* nums, int count)
{for (int i = 0; i < count; i++){printf("%d", nums[i]);if (i < count - 1) printf(",");}printf("\n");
}
//随机生成数组
void randomArray(int* nums, int numsSize, int min, int max)
{srand(time(0));for (int i = 0; i < numsSize; i++){nums[i] = rand() % max - min + 1 + min;//printf("%d,", nums[i]);}}
int sort(int* arr, int size)
{quickSort(arr, size);
}int main()
{//常量:测试数据大小,随机最小值,随机最大值const int size = 10000;const int min = 0;const int max = 10000;//预分配测试数据,临时空间数组,随机备份数组int* arr = malloc(sizeof(int) * size);int* tempArr = malloc(sizeof(int) * size);int* copy = malloc(sizeof(int) * size);randomArray(arr, size, min, max);memcpy(copy, arr, sizeof(int) * size);//计时器clock_t start, end;start = clock();//排序sort(arr,size);end = clock();end -= start;bool upper;//测试数据有序性检查bool res = checkArraySort(arr, size, &upper);//输出排序报告printf("========排序测试报告========\n");printf("元素数量:%d\n", size);printf("排序后有序检查(%s):%d\n", upper ? "升序" : "降序", res);printf("排序耗时(tick):%d\n", (int)end);printf("排序耗时(ms):%f\n", (double)(end * 1000) / CLOCKS_PER_SEC);printf("排序耗时(s):%f\n", (double)end / CLOCKS_PER_SEC);printf("\n是否打印排序前后元素(IO操作可能产生较大的耗时)(Y/N)?\n");char option;int inputC = scanf("%c", &option);if (option == 'Y' || option == 'y'){printf("\n排序前:");printElements(copy, size);printf("排序后:");printElements(arr, size);}
}
在第一篇中,我们首先做这些内容,接下来我们就能心无旁骛的编写排序函数了。
下文的链接如果写完会继续贴在这里(代码写完了,原理还没写)
传送门:十种排序算法(1) xxx