//
// main.c
// test1
//
// Created by yt on 2017/.
// Copyright © 2017年 yt. All rights reserved.
//
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
clock_t start, finish;
double duration;
int * selection_sort(int *arr,int len){
int i,j,min,temp,count=0;
for (i=0;i<len-1;i++){
min = i;
for(j=i+1;j<len;j++){
if(arr[min]>arr[j]){
min = j;
}
count++;
}
if(min!=i){
temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
}
}
printf(“count is %d\n”,count);
return arr;
}
int * bubble_sort(int *arr ,int len){
int i,j,temp,count=0;
for(i=0;i<len-1;i++){
for(j=0;j<len-1-i;j++){
if(arr[j]>arr[j+1]){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
count++;
}
}
printf(“count is %d\n”,count);
return arr;
}
void count_sort(int *arr, int *sorted_arr, int n)
{
int *count_arr = (int *)malloc(sizeof(int) * 100);
int i;
//初始化计数数组
for(i = 0; i<100; i++)
count_arr[i] = 0;
//统计i的次数
for(i = 0;i<n;i++)
count_arr[arr[i]]++;
//对所有的计数累加
for(i = 1; i<100; i++)
count_arr[i] += count_arr[i-1];
//逆向遍历源数组(保证稳定性),根据计数数组中对应的值填充到先的数组中
for(i = n; i>0; i–)
{
sorted_arr[count_arr[arr[i-1]]-1] = arr[i-1];
count_arr[arr[i-1]]–;
}
free(count_arr);
}
void printarr(int arr[],int len){
for(int i=0;i<len;i++){
printf(“%d,”,arr[i]);
}
}
int main(int argc, const char * argv[]) {
int arr[5],*sort_arr,count_sort_array[5];
arr[0]=3;arr[1]=9;arr[2]=0;arr[3]=20;arr[4]=6;
printf(“hello\n”);
printarr(arr,5);
printf(“\n\n”);
printf( “Time to do sort is “ );
start = clock();
count_sort(arr,count_sort_array,5);
finish = clock();
duration = (double)(finish – start) / CLOCKS_PER_SEC;
printf( “%f seconds\n”, duration );
printarr(count_sort_array,5);
return 0;
}