mirror of
https://github.com/TheAlgorithms/C
synced 2024-11-22 05:21:49 +03:00
Merge pull request #68 from AnupKumarPanwar/master
Merged 2 search algorithm folders
This commit is contained in:
commit
3cb33267bb
@ -1,39 +0,0 @@
|
||||
#include <stdio.h>
|
||||
|
||||
// Recursive Function- It returns location of x assumiung array arr[l..r] is present, otherwise -1
|
||||
|
||||
int binarysearch(int arr[], int l, int r, int x)
|
||||
{
|
||||
if (r >= l)
|
||||
{
|
||||
int mid = l + (r - l)/2;
|
||||
|
||||
// If element is present at middle
|
||||
if (arr[mid] == x) return mid;
|
||||
|
||||
// If element is smaller than middle
|
||||
if (arr[mid] > x) return binarysearch(arr, l, mid-1, x);
|
||||
|
||||
// Else element is in right subarray
|
||||
return binarysearch(arr, mid+1, r, x);
|
||||
}
|
||||
|
||||
// When element is not present in array
|
||||
return -1;
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
// give function an array to work with
|
||||
int arr[] = {2, 3, 4, 10, 40};
|
||||
// get size of array
|
||||
int n = sizeof(arr)/ sizeof(arr[0]);
|
||||
//set value to look for
|
||||
int x = 10;
|
||||
// set result to what is returned from binarysearch
|
||||
int result = binarysearch(arr, 0, n-1, x);
|
||||
// print out result
|
||||
(result == -1)? printf("Element is not in the array")
|
||||
: printf("Element is present at index %d", result);
|
||||
return 0;
|
||||
}
|
@ -1,40 +0,0 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
bool check_sorted(int *a, int n)
|
||||
{
|
||||
while ( --n >= 1 ) {
|
||||
if ( a[n] < a[n-1] ) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void shuffle(int *a, int n)
|
||||
{
|
||||
int i, t, r;
|
||||
for(i=0; i < n; i++) {
|
||||
t = a[i];
|
||||
r = rand() % n;
|
||||
a[i] = a[r];
|
||||
a[r] = t;
|
||||
}
|
||||
}
|
||||
|
||||
void sort(int *a, int n)
|
||||
{
|
||||
while ( !check_sorted(a, n) ) shuffle(a, n);
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
int numbers[6];
|
||||
int i;
|
||||
printf("Enter 6 numbers unsorted \n\n");
|
||||
for(i=0;i<6;i++){
|
||||
scanf("%d",&numbers[i]);
|
||||
}
|
||||
sort(numbers, 6);
|
||||
for (i=0; i < 6; i++) printf("%d ", numbers[i]);
|
||||
printf("\n");
|
||||
}
|
Loading…
Reference in New Issue
Block a user