开发者

insertion sort code using insert and insertsort! [closed]

开发者 https://www.devze.com 2023-01-17 09:43 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago.

i have written a code for insertion sort 开发者_开发知识库but it is nt sorting.. kindly help me out in making the desired changes to mycode. thanx

#include<stdio.h>

int compare(int a,int b)

{

if(a>b)

return 1;

else if( a<b)

return -1;

else if(a==b)

return 0;

}


void insert(int m, int ms[], int size)

{   

    int j,k;

    for (j=0; j<size; j++)   // Find the right position

       { if (compare(m, ms[j])) break;

    // Assertion: j is the right position for m

          for (k=size-1; k>=j; k--)  // Right shift values>m

       ms[k+1] = ms[k];

    ms[j] = m; } // Insert m

}



void insertSort(int ms[], int size)

{   

    int j;

    // Loop Invariant: 

    //  The sublist from ms[0] to ms[j-1] is sorted

    for (j=1; j<size; j++) {

         insert(ms[j], ms, j);

    }

}



void main()

{

int i,arr[5]={55,66,22,44,39};

printf("sorting\n");

insertSort(arr,5);



for( i=0;i<5;i++)

{

printf("\n%d",arr[i]);

}

}

this is my xact code.. i have to use the two functions insert and insert sort!


You're testing the return value of compare incorrectly. You probably want something like this:

if (compare(m, ms[j]) <= 0) break;

Also, remove the curly braces inside function insert, they are screwing the structure of your code. The statements following the break should not be inside the first loop's body.

By the way, if you make your code simpler and tidier, you'll be less likely to make silly mistakes. Proper indentation will help you visualize the structure of your code easily. For example:

void insort(int a[], int n, int e) {
    int j;
    for (j = n - 1; j >= 0 && a[j] > e; j--)
        a[j + 1] = a[j];
    a[j + 1] = e;
}
void insertion_sort(int a[], int n) { 
    int i;
    for (i = 1; i < n; i++)
        insort(a, i, a[i]);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消