M
M
MrChen2016-09-03 17:00:06
C++ / C#
MrChen, 2016-09-03 17:00:06

Why doesn't insert sort algorithm work in c++?

Hello! I started reading Cormen's Algorithms. The first algorithm I decided to try to implement is insertion sort... Here is the pseudo code: a1481b32b6f540e18e0d29f3ffb425fd.png
Here is the code I wrote in c++:

#include <iostream>

using namespace std;

int main() {
  int m[6] = {5, 2, 4, 6, 1, 3};
  int key = 0;
  int i = 0;

  int length = sizeof(m) / sizeof(int);

  for(int j = 2; j <= length; j++) {
    key = m[j];

    i = j - 1;
    
    while(i > 0 && m[j] > 0) {
      m[i + 1] = m[j];
      i = i - 1;
    }

    m[i + 1] = key;
  }
}

But for some reason it does not sort the array. Tell me why?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Zhilin, 2016-09-03
@MrChen

Indexing in C starts from 0, not from 1, as in many examples of algorithm implementations. Accordingly, if we see A[t], then we transfer it to C as A[t-1]

O
Oleg Filimonenko, 2018-02-25
@Redproxima

5a92f8b1af067174789070.pngI really hope my example helps someone. Same textbook, same problem. Example in C language. If there are errors or someone can give a recommendation for optimizing the algorithm, I'm waiting for comments.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i;
    int j;
    int key;
    int n;
    printf("Enter N; N - the size of Array\n");
    scanf("%d", &n);
    int A[n];

    for(i=0; i<=n-1; i++){
        printf("Enter A[%d] = ",i);
        scanf("%d", &A[i]);
    }
    for(j=1; j<=n-1; ++j){
        key = A[j];
        i=j-1;

        while(i>=0 && A[i]>key){
            A[i+1]=A[i];
            i=i-1;
        }
    A[i+1]=key;
    }
    for(i=0; i<=n-1; i++){
        printf("%d\ ", A[i]);

}
return 0;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question