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

151
ex1.cpp
View file

@ -3,112 +3,125 @@
#include <stdlib.h>
#include <time.h>
#define LENGTH 10000
int LENGTH;
//数组长度
bool RANDOM = false;
//是否随机生成数组
int MODE = 0;
//MODE_1: 迭代
//MODE_2: 递归
#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)
{
int c = *a;
*a = *b;
*b = c;
}
#ifdef MODE_1
void bobblesort1A(int a[],int n)
void bobblesort1A(int a[], int n)
{
bool sorted = false;
A:
sorted = true;
for(int i = 1 ; i < n ; i++)
{
if(a[i-1] > a[i])
{
swap(&a[i-1],&a[i]);
A:
sorted = true;
sorted=false;
}
for (int i = 1; i < n; i++)
{
if (a[i - 1] > a[i])
{
swap(&a[i - 1], &a[i]);
sorted = false;
}
n--;
if(sorted==false)
}
n--;
if (sorted == false)
goto A;
}
#elif defined MODE_2
void bobblesort1A(int a[],int n)
void bobblesort1B(int a[], int n)
{
bool sorted = false;
sorted = true;
for(int i = 1 ; i < n ; i++)
{
if(a[i-1] > a[i])
{
swap(&a[i-1],&a[i]);
sorted=false;
}
bool sorted = false;
sorted = true;
for (int i = 1; i < n; i++)
{
if (a[i - 1] > a[i])
{
swap(&a[i - 1], &a[i]);
sorted = false;
}
n--;
if(n==1)
}
n--;
if (n == 1)
return;
bobblesort1A(a,n);
bobblesort1B(a, n);
}
#endif
int main(){
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;
}
init();
clock_t start_t, end_t;
double total_t;
#ifdef OUTPUT
#ifdef OUTPUT
printf("Before\n");
for(int i=0;i<LENGTH;i++)
printf("%d \n",a[i]);
#endif
for (int i = 0; i < LENGTH; i++)
printf("%d \n", a[i]);
#endif
start_t = clock();
bobblesort1A(a,LENGTH);
bobblesort1C(a, LENGTH);
end_t = clock();
#ifdef OUTPUT
#ifdef OUTPUT
printf("After\n");
for(int i=0;i<LENGTH;i++)
printf("%d \n",a[i]);
#endif
for (int i = 0; i < LENGTH; i++)
printf("%d \n", a[i]);
#endif
printf("运算时间: %.4f 秒\n",((double)(end_t - start_t) / CLOCKS_PER_SEC));
printf("运算时间: %.4f 秒\n", ((double)(end_t - start_t) / CLOCKS_PER_SEC));
system("pause");
goto Begin;
}