#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/timeb.h>
#define MAX 100000
long getSystemTime()
{
struct timeb tb;
ftime(&tb);
return tb.time * 1000 + tb.millitm;
}
void Swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void PrintArray(int arr[], int length)
{
int i=0;
for(i = 0; i < length; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
// 冒泡排序
void BubbleSort(int arr[], int length)
{
int i=0,j=0;
for(i = 0; i < length; i++)
{
for(j = i + 1; j < length; j++)
{
if (arr[i] < arr[j])
{
Swap(&arr[i], &arr[j]);
}
}
}
}
// 选择排序
void SelectSort(int arr[], int length)
{
int i=0,j=0;
int min = 0;
for(i = 0; i < length; i++)
{
for(j = i + 1; j < length; j++)
{
if (arr[j] < arr[min])
{
min = j;
}
}
if (min != i)
{
Swap(&arr[min], &arr[i]);
}
}
}
// 希尔排序
void ShellSort(int arr[], int length)
{
int increasement = length;
int i, j, k;
do {
//确定分组的增量
increasement = increasement / 3 + 1;
for(i = 0; i < increasement; i++)
{
for(j = i + increasement; j < length; j += increasement)
{
if(arr[j] < arr[j - increasement])
{
int temp = arr[j];
for(k = j - increasement; k >= 0 && temp < arr[k]; k -= increasement)
{
arr[k + increasement] = arr[k];
}
arr[k + increasement] = temp;
}
}
}
} while (increasement > 1);
}
int main(void)
{
int arr_bubble[MAX];
int arr_select[MAX];
int arr_shell[MAX];
srand((unsigned int)time(NULL));
int i=0;
for(i = 0; i < MAX; i++)
{
arr_bubble[i] = rand() % MAX;
arr_select[i] = rand() % MAX;
arr_shell[i] = rand() % MAX;
}
//PrintArray(arr_bubble, MAX);
long tbubble_start = getSystemTime();
BubbleSort(arr_bubble, MAX);
long tbubble_end = getSystemTime();
//PrintArray(arr_bubble, MAX);
printf("冒泡排序%d个数,所需时间:%d\n", MAX, tbubble_end - tbubble_start);
printf("---------------------------------------\n");
//PrintArray(arr_select, MAX);
tbubble_start = getSystemTime();
SelectSort(arr_select, MAX);
tbubble_end = getSystemTime();
//PrintArray(arr_select, MAX);
printf("选择排序%d个数,所需时间:%d\n", MAX, tbubble_end - tbubble_start);
printf("---------------------------------------\n");
//PrintArray(arr_shell, MAX);
tbubble_start = getSystemTime();
ShellSort(arr_shell, MAX);
tbubble_end = getSystemTime();
//PrintArray(arr_shell, MAX);
printf("希尔排序%d个数,所需时间:%d\n", MAX, tbubble_end - tbubble_start);
return 0;
}