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

141
ex1.cpp
View file

@ -3,112 +3,125 @@
#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;
//随机数
void swap(int *a, int *b)
#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)
{ {
int c = *a; int c = *a;
*a = *b; *a = *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;
A: A:
sorted = true; sorted = true;
for(int i = 1 ; i < n ; i++) for (int i = 1; i < n; i++)
{
if (a[i - 1] > a[i])
{ {
if(a[i-1] > a[i]) swap(&a[i - 1], &a[i]);
{
swap(&a[i-1],&a[i]);
sorted=false;
}
sorted = false;
} }
n--; }
if(sorted==false) n--;
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;
for(int i = 1 ; i < n ; i++) for (int i = 1; i < n; i++)
{
if (a[i - 1] > a[i])
{ {
if(a[i-1] > a[i]) swap(&a[i - 1], &a[i]);
{
swap(&a[i-1],&a[i]);
sorted=false;
}
sorted = false;
} }
n--; }
if(n==1) n--;
if (n == 1)
return; 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(); init();
clock_t start_t, end_t; clock_t start_t, end_t;
double total_t; double total_t;
#ifdef OUTPUT #ifdef OUTPUT
printf("Before\n"); printf("Before\n");
for(int i=0;i<LENGTH;i++) for (int i = 0; i < LENGTH; i++)
printf("%d \n",a[i]); printf("%d \n", a[i]);
#endif #endif
start_t = clock(); start_t = clock();
bobblesort1A(a,LENGTH); bobblesort1C(a, LENGTH);
end_t = clock(); end_t = clock();
#ifdef OUTPUT #ifdef OUTPUT
printf("After\n"); printf("After\n");
for(int i=0;i<LENGTH;i++) for (int i = 0; i < LENGTH; i++)
printf("%d \n",a[i]); printf("%d \n", a[i]);
#endif #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"); system("pause");
goto Begin;
} }