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.




Your way doesn't work.
You sort `i' and `i+1', but you do not consider `i+2'

1
2
for(int j = i + 1; j < n - i - 1; ++j) {
   if (arr[i] > arr[i + 1]) {
if the condition is not met, you will check it `n' times
Last edited on
Topic archived. No new replies allowed.