diff --git a/ex1.cpp b/ex1.cpp index 6c34b1f..32e37aa 100644 --- a/ex1.cpp +++ b/ex1.cpp @@ -3,112 +3,125 @@ #include #include -#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