Untitled

 avatar
unknown
plain_text
4 years ago
2.1 kB
3
Indexable
#include <stdio.h>
#include "stdlib.h"



int* generate_random_array(int n)
{
		//create array of n elements
		int* arr=(int*)(malloc(n*sizeof(int));
		///int* arr=(int*)(calloc(n,sizeof(int));
		
		//initialize it with random numbers
	int seed=13;
	srandom(seed);
	int i;
		for(i=0;i<n;i++)
	{
		int rnd=(int)random();
		rnd=(int)(((double)rnd/(double)RAND_MAX*100.0));
		arr[i]=rnd;
	}
		return arr;
}

int* selection_sort(int* arr, int n)
{
	//implement selection sort
	int i;
	//loop to do n search for the minimum
	for(i=0;i<n;i++)
	{
		//for loop to find the minimum
		int min=arr[i];
		int min_idx=i;
		int j;
		for(j=i;j<n;j++)
	{
		if (min>arr[j])
	 	{min=arr[j];
	 	min_idx=j;}
	 	
	 	//swap the min found with the first element(exchange arr[i] with arr[min_idx]
	 	int temp=arr[i];
	 	arr[i]=arr[min_idx];
	 	arr[mon_idx]=temp;
	}

			
	}
}

int* binary_search(int* arr, int n,int val)
{
	int idx=-1;
	int start=0;
	int end=n-1;
	int middle;
	//*keep changing the start and the end variables depending of which part of the array the value might be*//
	for(;;)
	{
		middle=(start+end)/2;
		if(val>arr[middle]);
		{
			// we are in the right side of the array
			//change the start to the middle
			start=middle;
			if((end-start<2))
			{dx=start;
			return idx;}
			
			
		}
		else if(val<arr[middle])
		{
			//we are at the left side of the array
		
			//change the start to the middle
			end=middle;
			if((end-start<2))
			{dx=start;
			return idx;}
		}
		else
		{
			val=arr[middle];
			idx=middle;
			return idx;
		}
		
	} 
	
	
	
	return idx;
	

}


int print_array(int*arr,int n)
{
	int i;
	for(i=0;i<n;i++)
	{
		printf("%d, ",arr[i]);
	}		
	printf("\n");
}

int main()
{
	int n=20;
	int* arr=generate_random_array(n);
	//print the arrat before sorting
	print_array(arr,n);
	
	selection_sort(arr,n);
	//print the arrat before sorting
	print_array(arr,n);
int idx=binary_search(arr,n,arr[17])
printf("ifx= %d\n",idx);

}
Editor is loading...