V
V
Vadim kyklaed2018-02-14 13:42:33
C++ / C#
Vadim kyklaed, 2018-02-14 13:42:33

Is bubble sort done correctly?

Good afternoon! tell me if I did the sorting correctly?

#include <iostream>

using namespace std;

int main(){
  const int N = 9;
  int mass[N]={0,1000,401,-98,7,110,9,1332,0};
  
  for (int i=0;i<N;i++){
    for (int j=0;j<N-1;j++){
      if (mass[i]<mass[j]){
        double temp = mass[i];
        mass[i]=mass[j];
        mass[j]=temp;
      }
    }
  }
  for (int i=0;i<9;i++){
    cout<<mass[i]<<"\n";
  }
  return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlov, 2018-02-14
@kyklaed

Not quite right, but it's similar to bubble sort or simple exchange sort.

for (int i = 0; i < N; i++) {
    for (int j = N - 1; j > i; j--) {
        if (mass[j - 1] > mass[j]) {
            double temp = mass[j];
            mass[j] = mass[j - 1];
            mass[j - 1] = temp;
        }
    }
}

For example, insertion sort:
for (int i = 1; i < N; i++) {
    for (int j = i; j > 0 && mass[j - 1] > mass[j]; j--) {
        double temp = mass[j];
        mass[j] = mass[j - 1];
        mass[j - 1] = temp;
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question