[Data structures]Sequential search

2019-7-4 写技术

#include <stdio.h>
#include <stdlib.h>

int sequentialSearch(int seq[], int n, int x)
{
	int i;
	for (i = 0; i < n && x != seq[i]; i++) {
	}
	if (i==n) {
		return -1;
	} else {
		return i;
	}
}

int orderSequentialSearch(int seq[], int n, int x, int *is)
{
	int i;
	for (i=0; i < n && x > seq[i]; i++) {
	}
	*is = i;
	if (i < n && x == seq[i]){
		return i;
	} else {
		return -1;
	}
}

int binarySearch(int seq[], int n, int x, int *is)
{
	int mid;
	int left = 0;
	int right = n;
	while (left <= right) {
		mid = (left + right) / 2;
		if (x == seq[mid]) {
			return mid;
		} else if (x < seq[mid]) {
			right = mid - 1;
		} else {
			left = mid + 1;
		}
	}
	*is = left;
	return -1;
		
}

void main()
{
	int seq[] = {1,1,1,2,3,4,4,5,5,7,8,9,10};
	int n = sizeof(seq)/sizeof(int);
	int i;
	int is;

	printf("Original data:\n");
	for (i=0; i<n; i++) {
		printf(" %2d", seq[i]);
	}	
	printf("\n");

	printf("Sequential search:\n");
	printf("Search 6: %d \n", sequentialSearch(seq, n, 6));

	printf("Order sequential search:\n");
	i = orderSequentialSearch(seq, n, 6, &is);
	printf("Search 6: %d is=%d\n", i, is );

	printf("Binary search:\n");
	i = binarySearch(seq, n, 6, &is);
	printf("Search 6: %d is=%d\n", i, is );
}

标签: Data Structures data_structures

发表评论:

Powered by anycle 湘ICP备15001973号-1