void show_sort_result(const char* name,int* arr,size_t len)
{
printf("%10s:",name);
for(int i=0; i<len; i++)
{
printf("%d ",arr[i]);
}
printf("\n");
}
void bubble_sort(int* arr,size_t len)
{
bool flag = true;
for(int i=len-1; i>0 && flag; i--)
{
flag = false;
for(int j=0; j<i; j++)
{
if(arr[j] > arr[j+1])
{
swap(arr[j],arr[j+1]);
flag = true;
}
}
}
}
void select_sort(int* arr,size_t len)
{
for(int i=0; i<len-1; i++)
{
int min = i;
for(int j=i+1; j<len; j++)
{
if(arr[j] < arr[min])
min = j;
}
if(min != i)
swap(arr[min],arr[i]);
}
show_sort_result(__func__,arr,len);
}
void insert_sort(int* arr,size_t len)
{
for(int i=1,j; i<len; i++)
{
int tmp = arr[i];
for(j=i-1; j>=0 && tmp<arr[j]; j--)
{
arr[j+1] = arr[j];
}
arr[j+1] = tmp;
}
show_sort_result(__func__,arr,len);
}
void shell_sort(int* arr,size_t len)
{
for(int k=len/2; k>0; k/=2)
{
for(int i=k,j; i<len; i++)
{
int tmp = arr[i];
for(j=i-k; j>=0 && tmp<arr[j]; j-=k)
{
arr[j+k] = arr[j];
}
arr[j+k] = tmp;
}
}
show_sort_result(__func__,arr,len);
}
void create_heap(int* arr,size_t len,int root)
{
while(root*2 <= len)
{
int max = root*2;
if(max+1<len && arr[max-1] < arr[max])
max++;
if(arr[root-1] > arr[max-1])
return;
swap(arr[root-1],arr[max-1]);
root = max;
}
}
void heap_sort(int* arr,size_t len)
{
for(int i=len/2; i>0; i--)
create_heap(arr,len,i);
for(int i=len-1; i>0; i--)
{
swap(arr[0],arr[i]);
create_heap(arr,i,1);
}
show_sort_result(__func__,arr,len);
}
void _quick_sort(int* arr,int left,int right)
{
if(left >= right)
return;
int pi = left , pv = arr[left];
for(int l=left,r=right; l<r;)
{
while(l<r && pv<=arr[r]) r--;
if(l<r)
{
arr[pi]=arr[r];
pi = r;
}
while(l<r && arr[l] < pv) l++;
if(l<r)
{
arr[pi] = arr[l];
pi = l;
}
}
arr[pi] = pv;
_quick_sort(arr,left,pi-1);
_quick_sort(arr,pi+1,right);
}
void quick_sort(int* arr,size_t len)
{
_quick_sort(arr,0,len-1);
}
void merge_sort(int* arr,size_t len)
{
int *dest = malloc(sizeof(arr[0])*len), *src = arr;
for(int k=1; k<len; k*=2)
{
for(int i=0,j; i<len; i+=k*2)
{
int s1 = j= i , e1 = min(i+k,len);
int s2 = e1 , e2 = min(i+k*2,len);
while(s1 < e1 && s2 < e2)
{
dest[j++] = src[s1]<src[s2] ? src[s1++] : src[s2++];
}
while(s1 < e1)
dest[j++] = src[s1++];
while(s2 < e2)
dest[j++] = src[s2++];
}
swap(dest,src);
}
if(src != arr)
{
memcpy(arr,src,sizeof(arr[0])*len);
dest = src;
}
free(dest);
}
void count_sort(int* arr,int len)
{
int max = arr[0] , min = arr[0];
for(int i=1; i<len; i++)
{
if(max < arr[i])
max = arr[i];
if(min > arr[i])
min = arr[i];
}
int* count = calloc(sizeof(count[0]),max-min+1);
for(int i=0; i<len; i++)
{
count[arr[i]-min]++;
}
for(int i=0,k=0; i<=max-min; i++)
{
for(int j=0; j<count[i]; j++)
{
arr[k++] = i+min;
}
}
free(count);
show_sort_result(__func__,arr,len);
}
|