arrays - search and sorting in c program? -
i writing program receives numbers client , sort them bubble sorting function , other function receive 1 number client , search between other number binary search function .please inform me problem of program is?
#include <stdio.h> int bobsort (int); int searchi (int); void main () { int num, i; printf ("enter count number \n"); scanf ("%d", &num); int array[num]; (i = 1; <= num; i++) { printf ("enter number %d \n", i); scanf ("%d", &array[i - 1]); } bobsort (num); searchi (num); getch (); //return 0; } //**** function bobsort void bobsort (int n) { int c, d, swap; (c = 0; c < (n - 1); c++) { (d = 0; d < n - c - 1; d++) { if (array[d] > array[d + 1]) { /* decreasing order use < */ swap = array[d]; array[d] = array[d + 1]; array[d + 1] = swap; } } } printf ("sorted list in ascending order:\n"); (c = 0; c < n; c++) printf ("%d\n", array[c]); // return 0; } //**** function search int searchi () { int c, first, last, middle, n, search; printf ("enter value find\n"); scanf ("%d", &search); first = 0; last = n - 1; middle = (first + last) / 2; while (first <= last) { if (array[middle] < search) first = middle + 1; else if (array[middle] == search) { printf ("%d found @ location %d.\n", search, middle + 1); break; } else last = middle - 1; middle = (first + last) / 2; } if (first > last) printf ("not found! %d not present in list.\n", search); return 0; }
you had several compilation errors, below rewrote code comments can compile. actual functions seem work fine
the important change passing array
both functions. passed int*
functions can modify array
in context of main
#include <stdio.h> // neither 1 of these need return value, both void // both need have array passed, added int* void bobsort(int, int*); void searchi(int, int*); int main() { int num, i; printf("enter count number\n"); scanf("%d", &num); int array[num]; (i = 1; <= num; i++) { printf("enter number %d\n", i); scanf("%d", &array[i-1]); } // pass array both functions bobsort(num, array); searchi(num, array); // don't know supposed be, commented out //getch(); return 0; } // receives array main void bobsort(int num, int* array) { int c, d, swap; (c = 0; c < num-1; c++) { (d = 0; d < num-c-1; d++) { if (array[d] > array[d+1]) { swap = array[d]; array[d] = array[d+1]; array[d+1] = swap; } } } printf("sorted list in ascending order:\n"); (c = 0 ; c < num; c++) printf("%d\n", array[c]); } // receives array main void searchi(int num, int* array) { int c, first, last, middle, search; printf("enter value find\n"); scanf("%d", &search); first = 0; last = num-1; middle = (first+last)/2; while (first <= last) { if (array[middle] < search) first = middle+1; else if (array[middle] == search) { printf("%d found @ location %d\n", search, middle+1); break; } else last = middle-1; middle = (first+last)/2; } if (first > last) printf("not found! %d not present in list\n", search); }
Comments
Post a Comment