This commit is contained in:
iridiumR 2021-10-03 12:23:31 +08:00
parent 890cf727ef
commit 6b64f8a5f2

81
ex1.cpp
View file

@ -3,36 +3,18 @@
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
#define LENGTH 10000 int LENGTH;
//数组长度 //数组长度
bool RANDOM = false;
//是否随机生成数组
int MODE = 0;
//MODE_1: 迭代
//MODE_2: 递归
#define OUTPUT #define OUTPUT
//是否输出 //是否输出
// #define RANDOM int *a;
//随机数
#define MODE_1
//MODE_1: 迭代
//MODE_2: 递归
int a[LENGTH];
void init()
{
#ifdef RANDOM
srand(time(NULL));
#endif
for(int i = 0 ; i < LENGTH ; i++)
#ifdef RANDOM
a[i]=1+rand()%LENGTH;
#else
a[i]=LENGTH-i;
#endif
}
void swap(int *a, int *b) void swap(int *a, int *b)
{ {
@ -41,7 +23,6 @@ void swap(int *a,int *b)
*b = c; *b = c;
} }
#ifdef MODE_1
void bobblesort1A(int a[], int n) void bobblesort1A(int a[], int n)
{ {
bool sorted = false; bool sorted = false;
@ -56,16 +37,15 @@ void bobblesort1A(int a[],int n)
sorted = false; sorted = false;
} }
} }
n--; n--;
if (sorted == false) if (sorted == false)
goto A; goto A;
} }
#elif defined MODE_2 void bobblesort1B(int a[], int n)
void bobblesort1A(int a[],int n)
{ {
bool sorted = false; bool sorted = false;
sorted = true; sorted = true;
@ -77,17 +57,49 @@ void bobblesort1A(int a[],int n)
sorted = false; sorted = false;
} }
} }
n--; n--;
if (n == 1) if (n == 1)
return; return;
bobblesort1A(a,n); bobblesort1B(a, n);
}
void (*bobblesort1C)(int a[], int n);
void init()
{
srand(time(NULL));
a = new int[LENGTH];
for (int i = 0; i < LENGTH; i++)
if (RANDOM == true)
a[i] = 1 + rand() % LENGTH;
else
a[i] = LENGTH - i;
if (MODE == 1)
bobblesort1C = bobblesort1A;
else if (MODE == 2)
bobblesort1C = bobblesort1B;
}
int main()
{
Begin:
printf("输入数组长度:");
scanf("%d", &LENGTH);
printf("选择模式:1.迭代 2.递归");
scanf("%d", &MODE);
if ((MODE <= 0) || (MODE >= 3))
{
printf("错误输入\n");
goto Begin;
} }
#endif
int main(){
init(); init();
clock_t start_t, end_t; clock_t start_t, end_t;
double total_t; double total_t;
@ -99,7 +111,7 @@ int main(){
#endif #endif
start_t = clock(); start_t = clock();
bobblesort1A(a,LENGTH); bobblesort1C(a, LENGTH);
end_t = clock(); end_t = clock();
#ifdef OUTPUT #ifdef OUTPUT
@ -111,4 +123,5 @@ int main(){
printf("运算时间: %.4f 秒\n", ((double)(end_t - start_t) / CLOCKS_PER_SEC)); printf("运算时间: %.4f 秒\n", ((double)(end_t - start_t) / CLOCKS_PER_SEC));
system("pause"); system("pause");
goto Begin;
} }