Skip to content

Instantly share code, notes, and snippets.

@progapandist
Created May 20, 2015 11:36
Show Gist options
  • Save progapandist/f5c0d975dc0168d0e647 to your computer and use it in GitHub Desktop.
Save progapandist/f5c0d975dc0168d0e647 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdbool.h>
void bubblesort(int values[], int n);
bool binsearch(int values[], int value, int n);
int main(int argc, string argv[])
{
// Check if input is all digits. Exit if not.
for (int i = 1; i < argc; i++)
{
for (int j = 0, n = strlen(argv[i]); j < n; j++)
{
if (!isdigit(argv[i][j]))
{
printf("Your input should contain digits only. Try again!\n");
return 1;
}
}
}
// Convert arguments to integers.
// Store them into int array.
int numarray[argc];
for (int i = 1; i < argc; i++)
{
numarray[i] = atoi(argv[i]);
}
bubblesort(numarray, argc);
printf("Let me sort it out for you: ");
for (int i = 1; i < argc; i++)
printf("%i ", numarray[i]);
printf("\n");
printf("Okay, got it, what number do you want to find?\n");
int numToFind = GetInt();
binsearch(numarray, numToFind, argc) ?
printf("Look, it's here!\n") : printf("It's not there!\n");
}
void bubblesort(int array[], int n)
{
// cycle through array
for (int k = 0; k < n - 1; k++)
{
// optimize; check if there are no swaps
int swaps = 0;
// swap adjacent elements if out of order
// iterate through the array
for (int i = 0; i < n - 1 - k; i++)
{
//check if array[n] and array[n+1] are in order
if (array[i] > array[i+1])
{
int temp = array[i+1];
array[i+1] = array[i];
array[i] = temp;
swaps++;
}
}
if (!swaps)
break;
}
}
bool binsearch(int values[], int value, int n)
{
int lower = 0;
int upper = n - 1;
while (lower <= upper)
{
// find the middle
int middle = (upper + lower) / 2;
// compare middle to value wanted
if (values[middle] == value)
{
return true;
}
else if (values[middle] < value)
{
lower = middle + 1;
}
else if (values[middle] > value)
{
upper = middle - 1;
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment