Assuming you need a bubble sort, the general idea is (pseudo-code):
# The array to sort.
arr = [3, 1, 4, 1, 5, 9]
# Initially assume sorting needs a pass.
hasSwapped = true
while hasSwapped:
# If nothing swapped in this pass, we're done.
hasSwapped = false
# Check each element except last.
for idx = 0 to arr.sz - 2 inclusive:
# If bigger than next element, swap, flag another pass needed.
if arr[idx] > arr[idx + 1]:
temp = arr[idx]
arr[idx] = arr[idx + 1]
arr[idx + 1] = temp
hasSwapped = true
You should hopefully be able to understand the intent from the comments but the basic idea is:
- A single pass will check all elements and, if one is greater than the one after it, it will swap them.
- You have to do at least one pass.
- If a pass completes without a swap, the data is now sorted. Otherwise, more passes are needed.
Your job is now to convert that to the language of your choice.
I'll include an implementation below, with the function itself in C (though it will also work in C++, as evidenced by the surrounding test harness).
However, you would be unwise to assume educators don't perform plagiarism checks on assignments they give. In other words, don't use this code as-is, you'll almost certainly be caught out. Its intent is just to show you a possible implementation that you can compare your own code to:
#include <iostream>
using namespace std;
void bubbleSort(int *arr, size_t sz) {
int hasSwapped = 1;
while (hasSwapped) {
hasSwapped = 0;
for (size_t idx = 0; idx < sz - 1; ++idx) {
if (arr[idx] > arr[idx + 1]) {
int temp = arr[idx];
arr[idx] = arr[idx + 1];
arr[idx + 1] = temp;
hasSwapped = 1;
}
}
}
}
int main() {
int arr[] = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 9 };
for (size_t i = 0; i < sizeof(arr) / sizeof(*arr); ++i)
cout << arr[i] << ' ';
cout << '\n';
bubbleSort(arr, sizeof(arr) / sizeof(*arr));
for (size_t i = 0; i < sizeof(arr) / sizeof(*arr); ++i)
cout << arr[i] << ' ';
cout << '\n';
return 0;
}
The output is, as expected:
3 1 4 1 5 9 2 6 5 3 5 9
1 1 2 3 3 4 5 5 5 6 9 9