#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void BubbleSort(int arr[], int length);
void BubbleSort2(int arr[], int length);
int main(void)
{
srand((unsigned int)time(NULL));
int arr[10000];
for(int i=0;i<10000;i++){
int ret = rand()%10010+1;
arr[i]=ret;
}
int length = sizeof(arr) / sizeof(arr[0]);
clock_t start, finish;
double duration;
start = clock();
BubbleSort(arr,length);
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf( "平均%f seconds\n", duration );
BubbleSort2(arr, length);
start = clock();
BubbleSort(arr,length);
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf( "最坏%f seconds\n", duration );
return 0;
}
void BubbleSort(int arr[], int length)
{ int count=0;
for (int i = 0; i < length; i++)
{
for (int j = 0; j < length - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp;
temp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = temp;
count++;
}
}
}
printf("次数:%d\n",count);
}
void BubbleSort2(int arr[], int length)
{
for (int i = 0; i < length; i++)
{
for (int j = 0; j < length - i - 1; j++)
{
if (arr[j] < arr[j + 1])
{
int temp;
temp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = temp;
}
}
}
}