Answer the question
In order to leave comments, you need to log in
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:
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;
}
}
Answer the question
In order to leave comments, you need to log in
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]
I 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 questionAsk a Question
731 491 924 answers to any question