hello, i just set goal of mastering algorith and i just get started i have an algorhtm for insert sort and i when i write it in c it is not sorting this is the algorith

for j D 2 to A_length
key = A[j]
// Insert A[j] into the sorted sequence A[1..j-1]
i = j-1
while i > 0 and A[i] > key
A[i+1] = A[i] 
i = i-1
end while
A[i+1]= key
end for

and here is the c code

#include <stdio.h>
#define LENGHT 6
int main(void){
int j,i, key;
int arr[LENGHT];
for(j=0; j < LENGHT; j++){
  printf("enter value of [%d]\n", j);
  scanf("%d", &arr[j]);
}
printf("not sorted array: ");
for(j=0; j < LENGHT; j++){
  printf("%d,", arr[j]);
}
printf("\n");
for(j=1; j < LENGHT; j++){
  key = arr[j];
  i= j-1;
  while ( i > -1 && arr[j] > key){
    arr[i+1] = arr[i];
    i = i-1;
  }
  arr[i+1]=key;
}
printf("Sorted array: ");
for(j=0; j < LENGHT; j++){
  printf("%d,", arr[j]);
}
printf("\n");
return 0;
}

Recommended Answers

Rproffitt...
What's going on here? Who are you quoting?

Jump to Post

Then debug your code. Insert print statements so you can find out what it is doing or just go get another sort() function to replace this.

Sorting examples are abundant so no shortage there but I do find new programmers start off with missing debugging skills. To see what your …

Jump to Post

All 4 Replies

Algorith is a machine that uses kinetic energy in order to produce patterns.

I'd use a sort() function next time.

Rproffitt...
What's going on here? Who are you quoting?

commented: I worry their spelling may be causing other troubles. http://marcoiannicelli.com/portfolio-posts/algorith/ (the web) +12

sorry for the spelling i tried to edit but i couldn't , i'm talking about algorithm and no i dont want to use function sort () thank you all for replies

Then debug your code. Insert print statements so you can find out what it is doing or just go get another sort() function to replace this.

Sorting examples are abundant so no shortage there but I do find new programmers start off with missing debugging skills. To see what your code is doing, add prints or if you use a nice IDE, step step and examine what it is doing.