#include <stdio.h>
int main()
{
void bubbleSort(int a[], int n);
void slectionSort(int a[], int n);
void insertSort(int a[], int n);
int a[6] = {5, 2, 1, 0, 6, 3};
int b[6] = {5, 2, 1, 0, 6, 3};
int c[6] = {5, 2, 1, 0, 6, 3};
bubbleSort(a, 6);
slectionSort(b, 6);
insertSort(c, 6);
printf("the result of the bubble sort is:\n");
for (int i = 0; i < 6; i++)
{
printf("%d\n", a[i]);
}
printf("\n");
printf("the result of the selection sort is:\n");
for (int i = 0; i < 6; i++)
{
printf("%d\n", b[i]);
}
printf("the result of the selection sort is:\n");
for (int i = 0; i < 6; i++)
{
printf("%d\n", c[i]);
}
return 0;
}
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 + 1] < a[j])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
void slectionSort(int a[], int n)
{
int minIndex;
for (int i = 0; i < n - 1; i++)
{
minIndex = i;
for (int j = i + 1; j < n; j++)
{
if (a[j] < a[minIndex])
{
minIndex = j;
}
}
//交换a[i]和最小的那个数
int temp;
temp = a[i];
a[i] = a[minIndex];
a[minIndex] = temp;
}
}
void insertSort(int a[], int n)
{
int temp, j;
for (int i = 1; i < n; i++)
{
temp = a[i];
for (j = i; j > 0 && temp < a[j - 1]; j--)
/*注意:为什么要把 minNow < a[j - 1] 的这个条件写在注释里:
如果把minNow < a[j - 1] 写在for循环下面的一个if语句里
j的最后值一定是0,因此就找不到恰好要放进去的那个位置了;
*/
{
a[j] = a[j - 1];
}
a[j] = temp;
}
}
冒泡、选择、插入排序总结
最新推荐文章于 2024-07-19 17:11:32 发布