Revision as of 17:44, 5 May 2011 by Kumar43 (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
  1. include <stdio.h>
  2. include <stdlib.h>
  3. include <string.h>
  4. include <math.h>

int getRandomDouble() { return ((double) rand() / RAND_MAX); }

int getRandom(int min, int max) { return (max - min) * getRandomDouble() + min; }

void print_array(int *v, int items) { int i; for(i=0;i<items;i++) { printf("%d",v[1]); } printf("\n"); }


void selection_sort(int *v, int items) { int i; for(i=0;i<items-1;i++) { int min_ndx; int min_value = v[i]; int j;

// Find Minimum; for(j = i; j<items; j++) { if(v[j] < min_value) { min_value = v[j]; min_ndx; = j; } }

//Swap in the minimum to its rightful position v[min_ndx] = v[i]; v[i] = min_value; } }

int binary_search(int *v,int value, int min_ndx, int max_ndx) {


int mid_ndx = (max_ndx + min_ndx) / 2;

//Base step 1: is the element not here? if(min_ndx > max_ndx) { return -1; }


//Base Step 2: is this value the one? if(v[mid_ndx] == value) { return mid_ndx; }

//recursive steps: if(value < v[mid_ndx]) { return binary_search(v, value, min_ndx, mid_ndx-1); } else{ return binary_search(v, value, mid_ndx +1, max_ndx); } }

int linear_search(int *v, int value, int items) { int ndx; for(ndx = 0; ndx < items; ndx++) { if(v[ndx] == value) { return ndx; } } }


int main(int argc, char **argv) { const int NUM_ITEMS = 100; int v[NUM_ITEMS]; int i;

for(i=0;i<NUM_ITEMS;i++) { v[i] = getRandom(0,1000); }

print_array(v, NUM_ITEMS);

selection_sort(v,NUM_ITEMS);

printf("\n\nafter sorting: "); print_array(v,NUM_ITEMS);

printf("found 42 at index %d\n", binary_search(v,42, 0, NUM_ITEMS);

return 0; }


[['(**the format is not at basic coding standards due to the "Rhea" text editor)' ]]

Alumni Liaison

Questions/answers with a recent ECE grad

Ryne Rayburn