D
D
Dreaded2017-10-14 00:24:48
Algorithms
Dreaded, 2017-10-14 00:24:48

Is there a difference in the implementation of the sorting algorithm?

I started taking the CS50 course, after watching the lecture I wrote a bubble sort algorithm, my version:

int array[]={2,4,5,9,1,0,7,6,3,8};
    int counter;
    do
    {
        counter=0;
        for(int i=0; i < sizeof(array)/sizeof(array[0])-1; i++)
            {
                if(array[i]>array[i+1])
                {
                    int temp=array[i];
                    array[i]=array[i+1];
                    array[i+1]=temp;
                    counter++;
                }
            }
    }
    while (counter>0);

Then, of course, I went to google "how to do it right", and Wikibooks gives this option:
for(i = 0 ; i < n - 1; i++) { 
       // сравниваем два соседних элемента.
       for(j = 0 ; j < n - i - 1 ; j++) {  
           if(a[j] > a[j+1]) {           
              // если они идут в неправильном порядке, то  
              //  меняем их местами. 
              int tmp = a[j];
              a[j] = a[j+1] ;
              a[j+1] = tmp; 
           }
        }
    }

Is there a fundamental difference between these two options? If so, what is wrong with my version?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stalker_RED, 2017-10-14
@Stalker_RED

There is no fundamental difference, only the variable names are different and while instead of for
But do you know that this is one of the slowest algorithms?
https://www.youtube.com/watch?v=ZZuD6iUe3Pc

D
DVoropaev, 2017-10-14
@DVoropaev

Well, actually, you've optimized the sorting algorithm by adding a check to see if there were any changes during the inner for loop or not. That is, if the program comes across almost sorted arrays, then your code will work much faster.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question