129 lines
No EOL
2 KiB
C++
129 lines
No EOL
2 KiB
C++
#include <stdio.h>
|
|
// #include <iostream>
|
|
#include <stdlib.h>
|
|
#include <time.h>
|
|
|
|
int LENGTH;
|
|
//数组长度
|
|
int RANDOM = 0;
|
|
//是否随机生成数组
|
|
int MODE = 0;
|
|
//1: 迭代
|
|
//2: 递归
|
|
|
|
// #define OUTPUT
|
|
//是否输出
|
|
|
|
int *a;
|
|
|
|
void swap(int *a, int *b)
|
|
{
|
|
int c = *a;
|
|
*a = *b;
|
|
*b = c;
|
|
}
|
|
|
|
void bobblesort1A(int a[], int n)
|
|
{
|
|
bool sorted = false;
|
|
while (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--;
|
|
}
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|
|
n--;
|
|
if (n == 1)
|
|
return;
|
|
|
|
bobblesort1B(a, n);
|
|
}
|
|
|
|
void (*bobblesort)(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)
|
|
bobblesort = bobblesort1A;
|
|
else if (MODE == 2)
|
|
bobblesort = bobblesort1B;
|
|
}
|
|
|
|
int main()
|
|
{
|
|
Begin:
|
|
printf("是否随机生成数组(0/1):");
|
|
scanf("%d", &RANDOM);
|
|
|
|
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
|
|
printf("Before\n");
|
|
for (int i = 0; i < LENGTH; i++)
|
|
printf("%d \n", a[i]);
|
|
#endif
|
|
|
|
start_t = clock();
|
|
bobblesort(a, LENGTH);
|
|
end_t = clock();
|
|
|
|
#ifdef OUTPUT
|
|
printf("After\n");
|
|
for (int i = 0; i < LENGTH; i++)
|
|
printf("%d \n", a[i]);
|
|
#endif
|
|
|
|
printf("运算时间: %.4f 秒\n", ((double)(end_t - start_t) / CLOCKS_PER_SEC));
|
|
system("pause");
|
|
|
|
goto Begin;
|
|
} |