M.Stran94 - 8 months ago 69

C++ Question

Could someone please help to clarify what this question wants me to do as I haven't come across bubble sort before. Thanks

"Task 6 - Implementing a simple bubble sort with for…loops

Bubble sort is a fun little sorting mechanism that is relatively efficient for sorting small amounts of data into order. Study to following partial implementation of a Bubble sort and implement the highlighted missing code using appropriate nested

for loops."

`#include "stdafx.h"`

#include <stdio.h>

#include <iostream>

using namespace std;

int main()

{

int array[100], input, n, b, swap;

cout << "Enter number of elements\n";

cin >> n;

cout << "Enter " << n << " integers\n";

for (input = 0; input < n; input++)

cin >> array[input];

//add an outer for loop (b) from 0 to n-1

//{

//COM357 - Objected Oriented Programming Week 4

//include a nested for loop (c) from 0 to n – b - 1

//{

//if the item in array location ‘c’ > than the item in

//location c + 1, then swap these elements(hint: use a temp

// variable to store one of the item while you perform the

// swap).

// }

//}

cout << "Sorted list in ascending order:\n";

for (int output = 0; output < n; output++)

cout << array[output] << " \n";

return 0;

}

Answer

```
for (b=0; b<n-1; b++)
{
for (c=0; c<n-1-b; c++)
{
if (a[c+1] < a[c])/* compare the two neighbors */
{
temporary = array[c];
array[c] = array[c+1];
array[c+1] = temporary;
}
}
}
```

Source (Stackoverflow)