我猜你的第一个循环也是错误的,考虑到你想要实现Bubble Sort
,因为第一个循环告诉了对列表进行排序所需的通过次数。在冒泡排序的情况下,它等于Total Number of elements - 1
需要通过的次数来对 n 个元素的列表进行排序 (n - 1) 需要通过,因此i
如果我没记错的话,我的拙见必须从 1 开始。此外,就您在需要时声明变量而言,您提供的代码段与 C 语言编码风格不同。
第二个循环基本上是为了减少比较(元素数 - 通过 - 1),在每次迭代之后,因为每次通过,我们将最大的元素放在右侧(逻辑上未排序的列表)。因此,由于该元素处于其应有的位置,因此我们不必将其与其他元素进行比较。
4 3 2 1 Original List
3 2 1 4 Pass 1
-
Now since this above 4 is in it's rightful place
we don't need to compare it with other elements.
Hence we will start from the zeroth element and
compare two adjacent values, till 1 (for Pass 2)
Here comparison will take place between 3 and 2,
and since 3 is greater than 2, hence swapping
between 3 and 2, takes place. Now 3 is comapred
with 1, again since greater value is on left
side, so swapping will occur. Now 3 is not compared
with 4, since both these values are in their
rightful place.
2 1 3 4 Pass 2
-
Now since this above 3 is in it's rightful place
we don't need to compare it with other elements.
Hence we will start from the zeroth element and
compare two adjacent values, till 1 (for Pass 3)
Here only one comparison will occur, between
2 and 1. After swapping 2 will come to it's rightful
position. So no further comparison is needed.
1 2 3 4 Pass 3
Here the list is sorted, so no more comparisons, after Pass 3.
void bubbleSort(int *ptr, int size)
{
int pass = 1, i = 0, temp = 0;
for (pass = 1; pass < size - 1; pass++)
{
for (i = 0; i <= size - pass - 1; i++)
{
if (*(ptr + i) > *(ptr + i + 1))
{
temp = *(ptr + i);
*(ptr + i) = *(ptr + i + 1);
*(ptr + i + 1) = temp;
}
}
printf("Pass : %d\n", pass);
for (temp = 0; temp < size; temp++)
printf("%d\t", *(ptr + temp));
puts("");
}
}