R
R
randomguyasking2020-06-02 14:09:30
JavaScript
randomguyasking, 2020-06-02 14:09:30

How to count the number of operations while running a sorting algorithm?

Below is the code that implements the usual selection sort algorithm. Let me remind you that the complexity of this algorithm is O(n^2). I am passing an array of 7 elements to the sort function. If we calculate O(n^2), we get 7 * 7 = 49 operations. In the code, I'm trying to calculate the same thing by creating an operations variable and incrementing it at the end of each iteration of the loop, because an iteration is an operation (or isn't it?). In the end, I got 28, although I expected to see 49. Where is my mistake?

const sort = (collection) => {

let operations = 0;
const length = collection.length - 1;
  
  for (let i = 0; i <= length; i++) {
    let minIndex = i;
    for (let j = i + 1; j <= length; j++) {
      if (collection[j] < collection[minIndex]) {
        minIndex = j;
      }
      operations++;
    }
    if (minIndex !== i) {
      [collection[minIndex], collection[i]] = [collection[i], collection[minIndex]];
    }
    operations++
  }
  console.log('Количество операций: ', + operations);
  return collection;
};
console.log(sort([2, 1, 3, 5, 6, 3, 9]));

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
dmshar, 2020-06-02
@dmshar

I will tell you a little secret that you should have been told at the very first lecture on the theory of algorithms. If you take the same array, shuffle it and sort it again, then there is a high probability that you will get an answer other than 28.
And you must have been told that O (n) is not at all time and not even the number of operations that need to be done. In fact, O - notation shows how the number of executable operations changes with a corresponding increase in input data.
Accordingly, O(n) says that as the volume grows, the number of operations grows (approximately) linearly, and O(n^2) grows (approximately) quadratically.
If you want to be sure - you need to conduct such an experiment. Take a dataset with X elements, shuffle it 100,000 times, and sort it 100,000 times. You get some average number of repetitions A. Then you take a data set of 2X elements and repeat the procedure. You get the average number of operations B. And look at the ratio of B and A. This is a rough estimate of O (.).

O
origami1024, 2020-06-02
@origami1024

for (let i = 0; i <= length; i++) {
    let minIndex = i;
    for (let j = i + 1; j <= length; j++) {

You don't have O(N^2) complexity here.
The inner array does not count from beginning to end, but from the current element of the outer array.
You have something between O(NlogN) and O(N^2)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question