Tam*_*ash 5 c++ algorithm bubble-sort
我和朋友讨论过以下两种算法的真实冒泡类型,以及哪一种更好,没有提到哪一种是我的,我只是想听听你对这两个算法的两个问题的答案(用C++)
1 - 哪一个是真正的冒泡排序?
2哪个更好?
这是两种算法:
// Number one :
void BubbleSort(int Arr[], int size)
{ for (int i=0;i<size-1;i++)
for (int j=i+1;j<size;j++)
if (Arr[i]>Arr[j])
{ int temp = Arr[i];
Arr[i] = Arr[j];
Arr[j] = temp;
} }
// Number two :
void BubbleSort(int Arr[], int size)
{ for (int i=0;i<size-1;i++)
for (int j=0;j<size-1;j++)
if (Arr[j]>Arr[j+1])
{ int temp = Arr[j];
Arr[j] = Arr[j+1];
Arr[j+1] = temp;
} }
Run Code Online (Sandbox Code Playgroud)
Ste*_*ell 12
第二个更接近真实的一个.所有比较应该在相邻元素之间.
但真正的冒泡排序将采用while循环而不是外for循环,并且while只有在最后一次传递时必须交换元素时,循环才会再次执行,如下所示:
void BubbleSort(int Arr[], int size)
{
bool swapped;
do {
swapped = false;
for (int j=0;j<size-1;j++)
if (Arr[j]>Arr[j+1]) {
int temp = Arr[j];
Arr[j] = Arr[j+1];
Arr[j+1] = temp;
swapped = true;
}
} while (swapped);
}
Run Code Online (Sandbox Code Playgroud)