3

Say I have a list of numbers:

89 12 18 4 6

and I want to implement an insertion sort and have it print every step of the sort onto the screen:

Sort 1. 12 89 18 4 6
Sort 2. 4 12 89 18 6
Sort 3. 4 6 12 89 18
Sort 4. 4 6 12 18 89

here's the code that I have so far, I'm confused as to where to insert the printf inside the loop.

void insertion_sort(FILE *fp, int ar[15])
{
  int i, j, temp;

  for (i = 0; i < 15; i++)
    printf("%d\n", ar[i]);

  for(i = 0; i < 15; i++) {
    temp = ar[i];
    for(j = i - 1; j >= 0 && ar[j] > temp; j--)
        ar[j + 1] = ar[j];
    ar[j + 1] = temp;
}       
2
  • 1
    insert the printf() within the outer for loop, since you want to print the array you are sorting at each step. Commented Feb 11, 2013 at 8:00
  • does your sort even works? I guess you need to wrap 2nd for loops codes inside inner for loop Commented Feb 11, 2013 at 8:00

2 Answers 2

1

your scheme of sorting is actually Selection sort:

  Sort 1. 12 89 18 4 6 
  Sort 2. 4 12 89 18 6
  Sort 3. 4 6 12 89 18
  Sort 4. 4 6 12 18 89

it finds the smallest number and places it at the beginning of the list. A normal insertion sort would do the following:

  Sort 1. 12 89 18 4 6
  Sort 2. 12 18 89 4 6
  Sort 3. 4 12 18 89 6
  Sort 4. 4 6 12 18 89

and that is it finds 18 being less than 89 but greater than 12 and inserts 18 between 12 and 89 and the first iteration is done. Then repeat the process.

Here is my code:

void insertion(int *x,int n){ // int *x - array, n- array's length
    int i,j,k,temp,elem; // i,j,k - counters, elem - to store the element at pos x[i]
    for(i=0;i<n;i++){
        elem=x[i]; // store the element
        j=i; 
        while(j>0 && x[j-1]>elem){ // the magic(actual sorting)
            x[j]=x[j-1];
            j--;
        }
        x[j]=elem;  // swap the elements
        if(i>=1){   // here begins printing every sorting step, i>=1 because first time j is not greater than 0 so it just run through the loop first time
        printf("sort %d. ",i); // printing the step
        for(k=0;k<n;k++)    // loop through array 
            printf("%d ",x[k]); // display the elements already sorted
        printf("\n"); // when the array is displayed, insert a \n so that the next display will be on a new line
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

how is your code insertion sort and his code is not?Both are similar the only difference is the type of loop.
0

Put it at the end of the outer for statement just after ar[j + 1] = temp; and before the for loop ends

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.