You are using a version without Ads of this website. Please, consider donating:

### my sorting array style vs bubble sort

// this is my code
for(int i = 0; i < n; ++i) {
for(int j = i + 1; j < n - i - 1; ++j) {
if (arr[i] > arr[i + 1]) {

int tmp = arr[i];

arr[i] = arr[i + 1];

arr[i + 1] = tmp;
}
}

I want to know the (dis)advantage between my way and the bubble sort, thanks.

 void bubbleSort(int arr[], int n) { bool swapped = true; int j = 0; int tmp; while (swapped) { swapped = false; j++; for (int i = 0; i < n - j; i++) { if (arr[i] > arr[i + 1]) { tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; } } } }
you could use std::swap instead of that temp variable
or simply use std::sort

looks pretty much the same as bubble sort.
both have 2 loops
both swap in every step, if neccessary

try to just find the maximum in each run and then swap the higest index with the maximum.
that should be faster.

 ``12`` ``````for(int j = i + 1; j < n - i - 1; ++j) { if (arr[i] > arr[i + 1]) {``````