This repository has been archived on 2024-01-06. You can view files and clone it, but cannot push or open issues or pull requests.
justhomework/ex1.cpp

114 lines
1.6 KiB
C++
Raw Normal View History

2021-10-03 02:28:37 +00:00
#include <stdio.h>
// #include <iostream>
#include <stdlib.h>
#include <time.h>
#define LENGTH 10000
//<2F><><EFBFBD><EFBFBD><E9B3A4>
#define OUTPUT
//<2F>Ƿ<EFBFBD><C7B7><EFBFBD><EFBFBD><EFBFBD>
// #define RANDOM
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
#define MODE_1
//MODE_1: <20><><EFBFBD><EFBFBD>
//MODE_2: <20>ݹ<EFBFBD>
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("<EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʱ<EFBFBD><EFBFBD>: %.4f <20><>\n",((double)(end_t - start_t) / CLOCKS_PER_SEC));
system("pause");
}