#include <windows.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <ctime> #include <algorithm> #define ARRLEN 10000 using namespace std; int arr[ARRLEN],arr1[ARRLEN],arr2[ARRLEN],arr3[ARRLEN]; void BubbleSort(int arr[], int n) { for(int i=0;i<n-1; ++i) { for(int j=0;j<n-1-i;++j) { if(arr[j]>arr[j+1]) { swap(arr[j],arr[j+1]); } } } } void InsertSort(int arr1[],int n){ int i,j; for (i=1;i<n;i++) { for(j=i-1;j>=0&&arr1[j]>arr1[j+1];j--) swap(arr1[j],arr1[j+1]); } } void ShellSort(int arr2[],int n) { int i,j,gap; for (gap=n/2;gap>0;gap/=2) { for (i=gap;i<n;i++) { for(j=i-gap;j>=0&&arr2[j]>arr2[j+gap];j-=gap) swap(arr2[j],arr2[j+gap]); } } } int Patition(int arr3[], int low, int high) { int pivotkey=arr3[low]; int temp = arr3[low]; while(low<high) { while(low <high && arr3[high]>=pivotkey) { --high;; } arr3[low]=arr3[high]; while(low<high && arr3[low]<=pivotkey) { ++low;; } arr3[high]=arr3[low]; } arr3[low] = temp; return low; } void QuickSort(int arr3[], int low, int high) { if(low<high) { int pivotloc=Patition(arr3,low, high); QuickSort(arr3, low, pivotloc-1); QuickSort(arr3, pivotloc+1, high); } } void InitArr(){ for (int i=0,j;i<ARRLEN;i++) { j=rand()%10000; arr[i]=j;arr1[i]=j;arr2[i]=j;arr3[i]=j; } } void Display(int arr[],int n){ int i=0; while(n--){ printf("%d ",arr[i]); i++; } } int main(void){ DWORD start, stop; printf("BubbleSort:\n"); InitArr(); start = GetTickCount(); BubbleSort(arr,ARRLEN); stop = GetTickCount(); printf("time: %I64d ms\n", stop - start); //Display(arr,ARRLEN); printf("InsertSort:\n"); start = GetTickCount(); InsertSort(arr1,ARRLEN); stop = GetTickCount(); printf("time: %I64d ms\n", stop - start); //Display(arr,ARRLEN); printf("ShellSort:\n"); start = GetTickCount(); ShellSort(arr2,ARRLEN); stop = GetTickCount(); printf("time: %I64d ms\n", stop - start); //Display(arr,ARRLEN); printf("QuickSort:\n"); start = GetTickCount(); QuickSort(arr3,0,ARRLEN-1); stop = GetTickCount(); printf("time: %I64d ms\n", stop - start); //Display(arr,ARRLEN); getchar(); return 0; }