mirror of
https://github.com/RolandWH/ceesort.git
synced 2025-03-14 22:51:36 +00:00
added bubble sort algorithm
This commit is contained in:
parent
8091b93e68
commit
a3ea40e9fe
@ -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
20
src/bubble.c
Normal 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
5
src/bubble.h
Normal file
@ -0,0 +1,5 @@
|
||||
#pragma once
|
||||
#include <stddef.h>
|
||||
|
||||
|
||||
void bubblesort(int* arr, size_t n);
|
@ -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;
|
||||
|
Loading…
x
Reference in New Issue
Block a user