#include<iostream>
#include<algorithm>
#include"SortTestHelper.h"
using namespace std;
template<typename T>
void selectionSort(T arr[],int n){
for(int i=0;i<n;i++){
int min=i;
for(int j=i+1;j<n;j++){
if(arr[j]<arr[min]){
min=j;
}
}
swap(arr[i],arr[min]);
}
}
template<typename T>
void insertionSort(T arr[],int n){
for (int i=1;i<n;i++){
T e=arr[i];
int j;
for ( j=i;j>0&&arr[j-1]>e;j--){
arr[j]=arr[j-1];
}
arr[j]=e;
}
}
template<typename T>
void gudugudu(T arr[],int n){
for(int i=n-1;i>0;i--){
for(int j=0;j<i;j++){
if(arr[j]>arr[j+1]){
swap(arr[j],arr[j+1]);
}
}
}
}
const int INCRGAP=3;
template<typename T>
void shellsort(T arr[],int n){
int insertNum=0;
int gap=n/INCRGAP+1;
while(gap){
for(int i=gap;i<n;++i){
insertNum=arr[i];
int j=i;
while(j>=gap&&insertNum<arr[j-gap]){
arr[j]=arr[j-gap];
j-=gap;
}
arr[j]=insertNum;
}
gap=gap/INCRGAP;
}
}
int main(){
int n=10;
int *arr=SortTestHelper::generateRandomArray(n,0,n);
int *arr2=SortTestHelper::copyIntArray(arr,n);
int *arr3=SortTestHelper::generateNearlyOrderedArray(n,100);
int *arr4=SortTestHelper::copyIntArray(arr3,n);
shellsort(arr,n);
SortTestHelper::printArray(arr,n);
delete[] arr;
delete[] arr2;
delete[] arr3;
delete[] arr4;
system("Pause");
return 0;
}
#include<iostream>
#include<ctime>
#include<cassert>
using namespace std;
namespace SortTestHelper{
int* generateRandomArray(int n,int rangeL,int rangeR){
assert(rangeL<=rangeR);
int* arr=new int[n];
srand(time(NULL));
for(int i=0;i<n;i++)
arr[i]=rand()%(rangeR-rangeL+1)+rangeL;
return arr;
}
int* generateNearlyOrderedArray(int n,int swapTimes){
int *arr=new int[n];
for(int i=0;i<n;i++){
arr[i]=i;
}
srand(time(NULL));
for(int i=0;i<swapTimes;i++){
int posx=rand()%n;
int posy=rand()%n;
swap(arr[posx],arr[posy]);
}
return arr;
}
template<typename T>
void printArray(T arr[],int n){
for(int i=0;i<n;i++)
cout<<arr[i]<<" ";
cout<<endl;
return ;
}
template<typename T>
bool isSorted(T arr[],int n){
for(int i=0;i<n-1;i++)
if(arr[i]>arr[i+1])
return false;
return true;
}
template<typename T>
void testSort(string sortName,void(*sort)(T[],int),T arr[],int n){
clock_t startTime=clock();
sort(arr,n);
clock_t endTime=clock();
assert(isSorted(arr,n));
cout<<sortName<<":"<<double(endTime-startTime)/CLOCKS_PER_SEC<<"s"<<endl;
return;
}
int* copyIntArray(int a[],int n){
int* arr=new int[n];
copy(a,a+n,arr);
return arr;
}
}