#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define LEN 10
#define MAX_VAL 20
static int array[LEN];
void
print_array(void)
{
int i;
printf("printing\n");
for (i = 0; i < LEN; i++) {
printf("[%d] %d\n", i, array[i]);
}
}
void
init_array(void)
{
int i;
for (i = 0; i < LEN; i++) {
array[i] = rand() % MAX_VAL;
}
}
void
sort_array(void)
{
int i, j, tmp;
printf("sorting\n");
for (i = 0; i < LEN - 1; i++) {
for (j = 0; j < LEN - 1 - i; j++) {
if (array[j] > array[j + 1]) {
tmp = array[j];
array[j] = array[j + 1];
array[j + 1] = tmp;
}
}
}
}
void
binarysearch_array(void)
{
int l, u, m, val;
l = 0;
u = LEN - 1;
val = array[rand() % LEN];
printf("searching for %d\n", val);
while (l <= u) {
m = (l + u)/2;
if (array[m] == val) {
printf("found %d at %d :: %d\n", val, m, array[m]);
break;
} else if (array[m] > val) {
u = m - 1;
} else if (array[m] < val) {
l = m + 1;
}
}
}
int
main(int argc, char **argv)
{
srand(time(NULL));
init_array();
print_array();
sort_array();
print_array();
binarysearch_array();
return (0);
}
Friday, March 3, 2017
Simple examples of Bubble Sort and Binary Search in C
Using a LEN sized array (default size is 10), here's a quick and simple example of how to implement bubble sort and binary search routines in C.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment