int binarysearch double x int low int high double target int middle if low high

# Int binarysearch double x int low int high double

This preview shows page 8 - 13 out of 13 pages.

int binary_search (double x[], int low, int high, double target) { int middle; if (low > high) /*base case1:target not found*/ return -1; middle = (low + high)/2; if (x[middle] == target) return (middle); /*base case2:target found*/ else if (x[middle] < target) return binary_search(x, middle+1,high,target); else return binary_search(x, low, middle-1,target); }
9 Introduction to Sorting Sorting is the re-arrangement of a collection of data according to some key-field. It is a common activity in data management. Even when a list is maintained in a certain order, there is often a need to re-arrange the list in a different order. Because it takes so much processing time, sorting is a serious topic in computer science, and many different sorting algorithms have been designed. We shall consider two of such sorting methods; Selection sort and Bubble Sort.
10 Selection Sort Algorithm Selection sort involved scanning through the list to find (or select) the smallest element and swap it with the first element. The rest of the list is then search for the next smallest and swap it with the second element. This process is repeated until the rest of the list reduces to one element, by which time the list is sorted. The following table shows how selection sort works.
11 Selection Sort Implementation #include <stdio.h> #define SIZE 10 void selection_sort(double a[], int size); void read_array(double a[], int size); void print_array(double a[], int size); int find_min(double a[], int start, int size); void swap(double *a, double *b); int main(void) { double x[SIZE]; int i; read_array(x, SIZE); printf("Before Sorting: "); print_array(x, SIZE); selection_sort(x, SIZE); printf("After Sorting: "); print_array(x, SIZE); system("pause"); return 0; } void selection_sort(double a[], int size) { int i, min_pos; for (i = 0; i<=size-2; i++) { min_pos = find_min(a, i, size); swap(&a[i], &a[min_pos]); } } int find_min(double a[], int start, int size) { int i, min_index = start; for (i=start+1; i<size; i++) if (a[i] < a[min_index]) min_index = i; return min_index; } void swap(double *a, double *b) { double temp = *a; *a = *b; *b = temp; } void read_array (double a[], int size) { int i; printf("Enter %d integer numbers separated by blanks\n> ", size); for (i = 0; i < size; ++i) scanf("%lf", &a[i]); } void print_array(double a[], int size) { int i; for (i = 0; i < size; ++i) printf("%.1f ", a[i]); printf("\n"); }
12

#### You've reached the end of your free preview.

Want to read all 13 pages?

• Spring '10
• baleh
• int size