'What is the wrong point of my insertion sort sample program
While I practice C
,I developed sample insertion sort
in C
. after some search and refer some materials ,I wrote following one. After that,I build and run.
gcc insertion.c
./a.out
But it didn't show anything. What is the wrong point of that? As I am completely beginner,if someone notice important point. will you please let me know.
#include<stdio.h>
// show element in each array
void trace(int A[], int N){
int i;
for (i =0; i<N; i++){
if(i>0) printf(" ");
printf("%d",A[i]);
}
printf("\n");
}
// insertion sort
void insertionSort(int A[],int N){
int j,i,v;
for(i=1;i<N;i++){
v = A[i];
j = i - 1;
while( j > 0 && A[j] > v){
A[j + 1] = A[j];
j--;
}
A[j+1]=v;
trace(A,N);
}
}
int main(){
int N, i, j;
int A[100];
scanf("%d", &N);
for (i = 0;i < N;i++) scanf("%d", &A[i]);
trace(A,N);
insertionSort(A,N);
return 0;
}
Thanks
Solution 1:[1]
You don't see anything because the program is waiting for input - scanf
blocks the program until the user enters something.
int main()
{
int N, i, j;
int A[100];
printf("Enter N: ");
scanf("%d", &N);
for (i = 0;i < N;i++){
printf("Enter %d: ",i);
scanf("%d", &A[i]);
}
trace(A,N);
insertionSort(A,N);
return 0;
}
Try the above code. If I understand you correctly, you are trying to sort an array. It works, but then shows you different things that may be isn't well.
I hope I've helped.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | codeling |