- include <stdio.h>
- include <stdlib.h>
- include <string.h>
- 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)'
]]