我目前学到的常见的有三种排序方法 插入,选择和冒泡排序 。
这里面我觉得插入排序是最难理解的
这次我是结合指针来操作数组
这个是插入排序
#include <stdio.h>
void insert(int *p, int n)
{
int i, j, temp;
for (i = 1; i < n; i++)
{
temp = *(p + i);
for (j = i - 1; j >= 0 && temp < *(p + j); j--)//将大于temp的元素循环后移
*(p + j + 1) = *(p + j);
*(p + j + 1) = temp;
}
}
int main()
{
int a[10] = {78, 34, 54, 23, 780, 64, 45, 75, 34, 66};
insert(a, 10);
for (int i = 0; i < 10; i++)
printf("%d ",a[i]);
printf("\n");
return 0;
}
这是选择排序
#include <stdio.h>
void selectsort(int *p, int n)
{
int i, j, *pt, temp;
for (i = 0; i < n; i++)
{
pt = p + i;
for (j = i + 1; j < n; j++)
{
if (*(p + j) < *pt)
pt = p + j;
}
temp = *pt, *pt = *(p + i), *(p + i) = temp;
}
}
int main()
{
int a[10] = {78, 34, 54, 23, 780, 64, 45, 75, 34, 66};
selectsort(a, 10);
for (int i = 0; i < 10; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
这是冒泡排序
#include <stdio.h>
void bubblesort(int *p, int n)
{
int i, j, temp;
for (int i = n - 1; i >= 0; i--)
{
for (j = 0; j < i; j++)
{
if (*(p + j) > *(p + j + 1))
{
temp = *(p + j + 1);
*(p + j + 1) = *(p + j);
*(p + j) = temp;
}
}
}
}
int main()
{
int a[10] = {78, 34, 54, 23, 780, 64, 45, 75, 34, 66};
bubblesort(a, 10);
for (int i = 0; i < 10; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}