You are on page 1of 2

Median Search: Given an UNSORTED array, find the median.

For example, let the array be {3, 8, 7, 2, 1} then your program should print median as 3. Approach 1 (Use Sorting) 1) Sort the given array using an efficient sorting algorithm (preferably Quick Sort). 2) Return the middle element in the sorted array. Approach 2 (Do not sort everything) 1) Design a method to find the kth smallest element using partition() function of Quick Sort. 2) Use the method designed in step 1 to find out the middle element. In case n is odd, pass appropriate argument of k to the method. For n is even, call the method twice with appropriate arguments, and return average of two values.

#include<stdio.h> int partition(int A[], int l, int r); void printArray(int A[], int size) { int i; for(i=0; i < size; i++) printf("%d ", A[i]); printf("\n"); } int kthElement(int arr[], int l, int r, int k) { int i, pos; if(k <= r - l + 1) { if(l == r) return arr[l]; i = partition(arr, l, r); pos = i - l; if( pos == k - 1) return arr[i]; else if(pos > k - 1) return kthElement(arr, l, i-1, k); else /* i < k-1 */ return kthElement(arr, i+1, r, k - pos - 1); } else return -1;

} void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } int partition(int A[], int l, int r) { int x = A[r]; int i = l; int j; for(j = l; j <= r - 1; j++) { if(A[j] <= x) { swap(&A[i], &A[j]); i++; } } swap(&A[i], &A[r]); return i; } int main() { int arr[] = {1, 2, 3, 6, 7, 5, 9}; int n = sizeof(arr)/sizeof(arr[0]); printf("\n Median is %d ", kthElement(arr, 0, n-1, 4)); getchar(); return 0; }

You might also like