选择排序
选择排序是一种时间复杂度为O(n^2)的排序算法,主要步骤就是不断的从待排的数据集合中找到最小或者最大的索引位置,然后交换到已经排好的数据集合的尾部。选择排序一般需要两层遍历,一层控制排好的集合的位置,一层是控制不断从待排的数据中找到最小或者最大的数据。因此时间复杂度为O(n^2)。
代码实现
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void benchmak(const char *name, void (*func)(int *arry, int), int arry[], int n)
{
clock_t startTime = clock();
func(arry, n);
clock_t endTime = clock();
printf("%s : %lfs\n", name, (double)(endTime - startTime) / CLOCKS_PER_SEC);
}
int* generateRandomArray(int n, int rangL, int rangR)
{
int* array = malloc(n *sizeof(int));
if(array == NULL)
return NULL;
srand(time(NULL));
for(int i = 0; i < n; i++)
{
array[i] = rand() % (rangR - rangL + 1) + rangL;
}
return array;
}
void selectSort(int arry[], int n)
{
int tmp;
for(int i = 0; i < n; i++) //控制已经排好的位置
{
int minIndex = i; //从待排的数据中找出最小的元素位置
for(int j = i + 1; j < n; j++)
{
if(arry[j] < arry[minIndex])
{
minIndex = j;
}
}
if(minIndex != i)
{
tmp = arry[i]; //交换元素
arry[i] = arry[minIndex];
arry[minIndex] = tmp;
}
}
}
int main(int argc, char *argv[])
{
//int arry[10] = {10, 7, 8, 9, 6, 4, 2, 3, 1, 5};
int n = 10;
int* arry = generateRandomArray(n, 1, 10);
if(arry == NULL)
return 0;
for(int i = 0; i < n; i++)
{
printf("%d\t", arry[i]);
}
printf("\n-------------------------------\n");
//selectSort(arry, n);
benchmak("selectSort", selectSort, arry, n);
for(int i = 0; i < n; i++){
printf("%d\t", arry[i]);
}
printf("\n");
if(arry) free(arry);
return 0;
}
编译和执行:
root@ubuntu:~/DataStruct/day1$
root@ubuntu:~/DataStruct/day1$ gcc selectsort.c -o selectsort
root@ubuntu:~/DataStruct/day1$
root@ubuntu:~/DataStruct/day1$
root@ubuntu:~/DataStruct/day1$
root@ubuntu:~/DataStruct/day1$
root@ubuntu:~/DataStruct/day1$ ./selectsort
6 5 10 6 3 10 5 4 1 1
-------------------------------
selectSort : 0.000002s
1 1 3 4 5 5 6 6 10 10
root@ubuntu:~/DataStruct/day1$
root@ubuntu:~/DataStruct/day1$ vi selectsort.c
root@ubuntu:~/DataStruct/day1$
root@ubuntu:~/DataStruct/day1$
root@ubuntu:~/DataStruct/day1$ gcc selectsort.c -o selectsort
root@ubuntu:~/DataStruct/day1$
root@ubuntu:~/DataStruct/day1$ ./selectsort
42 42 48 43 33 77 27 57 87 31 14 86 81 21 66 64 90 5467 28 14 84 87 80 43 19 24 21 34 68 65 27 9 12 69 9440 48 50 27 78 63 12 58 35 29 22 76 83 40 3 48 23 4180 17 60 3 37 45 71 53 72 31 17 92 24 56 39 25 34 1639 45 26 73 74 99 49 8 38 3 7 60 44 86 77 55 89 6599 11 18 70 41 34 14 17 41 52
-------------------------------
selectSort : 0.000048s
3 3 3 7 8 9 11 12 12 14 14 14 16 17 17 17 18 1921 21 22 23 24 24 25 26 27 27 27 28 29 31 31 33 34 3434 35 37 38 39 39 40 40 41 41 41 42 42 43 43 44 45 4548 48 48 49 50 52 53 54 55 56 57 58 60 60 63 64 65 6566 67 68 69 70 71 72 73 74 76 77 77 78 80 80 81 83 8486 86 87 87 89 90 92 94 99 99
root@ubuntu:~/DataStruct/day1$
root@ubuntu:~/DataStruct/day1$
root@ubuntu:~/DataStruct/day1$