c - Sorting an array with Insertion Sort -
my task write function naive_sort() takes array of random generated integers parameter , sorts them. need use insertion sort. have come point have no idea how fix problem, when run program nothing happens. console stays empty.i'm new c programming don't surprised if find stupid mistake somewhere. appreciated.
edit: it's outputting list of numbers not being sorted, output example:
558915997481717626 152655717476818999 this code(edited):
#include <stdio.h> #include<conio.h> #include <stdlib.h> #include <time.h> //insertion sort function sort integer array list int *naive_sort(int array[],int n) { int j,temp,i; //iterate start second element (i = 1; < n; i++) { j = i; //iterate , compare till satisfies condition while ( j > 0 && array[j] < array[j-1]) { //swapping operation temp = array[j]; array[j] = array[j-1]; array[j-1] = temp; j--; } } //return sorted array return array; } int main() { //declaring variables int array[10],i; int n = 10; srand (time(null)); //initialize random seed (i=0; i<n; i++) { array[i] = rand() % 100; scanf("%d",&array[i]); } for(i=0; i<n; i++) { printf("%d", array[i]); } printf("\n"); //calling naive_sort function defined above , getting //sorted array in sortarray variable naive_sort(array,n); //print sorted array for(i = 0; i<n; i++ ) { printf("%d",array[i]); } printf("\n"); return 0; }
you didn' t initialze local variable n, there return statment in middle of code, access array out of bounds in first for loop (because of <=100). adapt code this:
#include <stdio.h> // printf, scanf #include <stdlib.h> // srand, rand #include <time.h> // time int main() { int array[100], i; int n = 100; // init n srand (time(null)); // initialize random seed for( i=0; i<n; i++ ) { array[i] = rand() % 100; // replace scanf read values input // scanf("%d",&array[i]); } for( i=0; i<n; i++ ) { printf("%4d",array[i]); } printf( "\n" ); naive_sort(array,n); // sort array for( i=0; i<n; i++ ) { printf("%4d", array[i]); } printf( "\n" ); return 0; } your function naive_sort works expected.
Comments
Post a Comment