added bubble sort algorithm

This commit is contained in:
Roland W-H 2022-04-01 10:34:34 +01:00
parent 8091b93e68
commit a3ea40e9fe
4 changed files with 70 additions and 12 deletions

View File

@ -6,6 +6,7 @@
int bsrch(int target, int* arr, size_t n)
{
// TODO: Find a way to error if list is out of order
bool found = false;
int start = 0, end = n - 1;
if (arr[start] > target || arr[end] < target) return -1;

20
src/bubble.c Normal file
View File

@ -0,0 +1,20 @@
#include "bubble.h"
#include <stdbool.h>
void bubblesort(int* arr, size_t n)
{
for (int i = 0; i < n; i++)
{
for (int elem = 0; elem < n - 1 - i; elem++)
{
if (arr[elem] > arr[elem + 1])
{
int temp = arr[elem];
arr[elem] = arr[elem + 1];
arr[elem + 1] = temp;
}
}
}
}

5
src/bubble.h Normal file
View File

@ -0,0 +1,5 @@
#pragma once
#include <stddef.h>
void bubblesort(int* arr, size_t n);

View File

@ -1,3 +1,4 @@
#include "bubble.h"
#include "bsrch.h"
#include <ctype.h>
@ -13,6 +14,7 @@ bool isint(char* s)
if (s[i] == '-' && isdigit(s[i + 1])) continue;
if (!isdigit(s[i])) return false;
}
return true;
}
@ -29,7 +31,26 @@ int main(int argc, char** argv)
}
arr[i - 1] = atoi(argv[i]);
}
int n = argc - 1;
char choice_str[16];
printf(
"1. Binary search\n"
"2. Bubble sort\n"
"Please pick a mode of operation: "
);
scanf("%s", choice_str);
// Add checking that number is in range
while (!isint(choice_str))
{
printf("Sorry but you must enter a number between 1 and 2\n");
printf("Try again: ");
scanf("%s", choice_str);
}
int choice = atoi(choice_str);
if (choice == 1)
{
char target_str[16];
printf("Enter number to search for: ");
scanf("%s", target_str);
@ -40,11 +61,22 @@ int main(int argc, char** argv)
}
int target = atoi(target_str);
int result = bsrch(target, arr, argc - 1);
int result = bsrch(target, arr, n);
if (result == -1)
puts("Value not found");
else
printf("Value found at index: %d\n", result);
}
else if (choice == 2)
{
bubblesort(arr, n);
printf("Here is your sorted list:\n");
for (int i = 0; i < n; i++)
{
printf("%d", arr[i]);
if (i < n - 1) printf(", ");
}
}
free(arr);
return 0;