114 lines
No EOL
1.6 KiB
C++
114 lines
No EOL
1.6 KiB
C++
#include <stdio.h>
|
|
// #include <iostream>
|
|
#include <stdlib.h>
|
|
#include <time.h>
|
|
|
|
#define LENGTH 10000
|
|
//数组长度
|
|
|
|
#define OUTPUT
|
|
//是否输出
|
|
|
|
// #define RANDOM
|
|
//随机数
|
|
|
|
|
|
#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;
|
|
*a = *b;
|
|
*b = c;
|
|
}
|
|
|
|
#ifdef MODE_1
|
|
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]);
|
|
|
|
sorted=false;
|
|
}
|
|
|
|
}
|
|
n--;
|
|
if(sorted==false)
|
|
goto A;
|
|
}
|
|
|
|
#elif defined MODE_2
|
|
void bobblesort1A(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;
|
|
|
|
bobblesort1A(a,n);
|
|
}
|
|
#endif
|
|
|
|
int main(){
|
|
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();
|
|
bobblesort1A(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");
|
|
|
|
} |