cs-2124(lab): add first lab assignment

This commit is contained in:
Price Hiller 2024-02-01 10:45:55 -06:00
parent 9795a45502
commit 59a6b9b5f3
Signed by: Price
SSH Key Fingerprint: SHA256:Y4S9ZzYphRn1W1kbJerJFO6GGsfu9O70VaBSxJO7dF8
6 changed files with 79 additions and 0 deletions

View File

@ -0,0 +1,9 @@
cmake_minimum_required(VERSION 3.25)
set(SOURCES src/lib.h src/lib.c src/main.c)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY bin)
project(LabOne LANGUAGES C)
add_executable(labone ${SOURCES})

View File

@ -0,0 +1,13 @@
* Lab Work - Sorting and Binary Search
Get an array of integer, the target integer, then sort the array and find the target using binary
search
- Create a library for binary search and a sorting algorithm to sort the array and use it in main
file
- Input:
- First line contains one integer $n$, the size of the array
- Second line contains $n$ integers $a_i$, elements of the array
- Third line contains hte search integer/key $m$
- Output:
- Print hte location of the search integer $m$ in the given array. If not found, print =-1=.
Submit the zipped folder

Binary file not shown.

View File

@ -0,0 +1,28 @@
int binary_search(int arr[], int m, int size) {
int low = 0;
int high = size - 1;
while (low != high) {
int mid = (low + high) / 2;
if (m == arr[mid]) {
return mid;
} else if (m > arr[mid]) {
low = mid + 1;
} else {
high = mid - 1;
};
}
return -1;
}
void bubble_sort(int a[], int n) {
int i = 0, j = 0, tmp;
for (i = 0; i < n; i++) {
for (j = 0; j < n - i - 1; j++) {
if (a[j] > a[j+1]) {
tmp = a[j];
a[j] = a[j+1];
a[j + 1] = tmp;
}
}
}
}

View File

@ -0,0 +1,5 @@
#ifndef CUST_LIB
#define CUST_LIB
int binary_search(int arr[], int m, int size);
void bubble_sort(int a[], int n);
#endif // !CUST_LIB

View File

@ -0,0 +1,24 @@
#include "./lib.h"
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("Enter size of array: ");
int arr_size = -1;
scanf("%d", &arr_size);
int arr[arr_size];
printf("Enter elements:\n");
for (int i = 0; i < arr_size; i++) {
scanf("%d", &arr[i]);
}
int m = 0;
printf("Enter search element: ");
scanf("%d", &m);
bubble_sort(arr, arr_size);
printf("Sorted elements to search in: ");
for (int i = 0; i < arr_size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
int location = binary_search(arr, m, arr_size);
printf("Location of %d was found at %d\n", m, location);
}