三种最简单基础的排序 选择排序 冒泡排序 直接插入排序 运用了函数指针数组

来源:互联网 发布:矩阵各元素之和叫什么 编辑:程序博客网 时间:2024/05/01 09:54
#include <stdio.h>
#include <stdlib.h>
#include <time.h>


void CreateArray(int *a, int n);
void PrintArray(int *a, int n);
void BubbleSort(int *a, int n);
void SelectSort(int *a, int n);
void InsertSort(int *a, int n);


int main()
{
int a[10];
int select;


CreateArray(a, 10);
PrintArray(a, 10);


void (*p[3])(int *, int) = {BubbleSort, InsertSort, SelectSort};


printf("Which Sort do you prefer?\n");
printf("1 BubbleSort\n");
printf("2 InsertSort\n");
printf("3 SelectSort\n");


scanf("%d",&select);


(p[select - 1])(a, 10);


PrintArray(a, 10);


return 0;
}


void InsertSort(int *a, int n)
{
    int temp;
for (int i = 1; i < n; ++i)
{
temp = a[i];
int j;
for (j = i - 1; j >= 0 && a[j] > temp; --j)
{
a[j + 1] = a[j];
}
a[j + 1] = temp;
}
}


void SelectSort(int *a, int n)
{
    int min;
    int temp;
for (int i = 0; i < n - 1; ++i)
{
   min = i;
for (int j = i + 1; j < n; ++j)
{
if (a[min] > a[j])
{
min = j;
}
}
if (min != i)
{
temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}
}


void BubbleSort(int *a, int n)
{
int temp;
for (int i = 0; i < n - 1; ++i)
{
for (int j = 0; j < n - i - 1; ++j)
{
if(a[j] > a[j + 1])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}




void PrintArray(int *a, int n)
{
for (int i = 0; i < n; ++i)
{
printf("%d\n", a[i]);
}
}




void CreateArray(int *a, int n)
{
srand(time(NULL));
for (int i = 0; i < n; ++i)
{
a[i] = rand()%100 + 1;
}
}
0 0