TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
|
Implementation of Median search algorithm. @cases from here More...
#include <iostream>
#include <algorithm>
#include <vector>
#include <cassert>
Go to the source code of this file.
Namespaces | |
namespace | search |
for std::assert | |
namespace | median_search |
Functions for Median search algorithm. | |
Functions | |
int | search::median_search::median_of_medians (const std::vector< int > &A, const int &idx) |
void | test () |
int | main () |
Implementation of Median search algorithm. @cases from here
Given an array A[1,...,n] of n numbers and an index i, where 1 ≤ i ≤ n, find the i-th smallest element of A. median_of_medians(A, i): #divide A into sublists of len 5 sublists = [A[j:j+5] for j in range(0, len(A), 5)] medians = [sorted(sublist)[len(sublist)/2] for sublist in sublists] if len(medians) <= 5: pivot = sorted(medians)[len(medians)/2] else: #the pivot is the median of the medians pivot = median_of_medians(medians, len(medians)/2) #partitioning step low = [j for j in A if j < pivot] high = [j for j in A if j > pivot] k = len(low) if i < k: return median_of_medians(low,i) elif i > k: return median_of_medians(high,i-k-1) else: #pivot = k return pivot
Here are some example lists you can use to see how the algorithm works A = [1,2,3,4,5,1000,8,9,99] (Contain Unique Elements) B = [1,2,3,4,5,6] (Contains Unique Elements) print median_of_medians(A, 0) #should be 1 print median_of_medians(A,7) #should be 99 print median_of_medians(B,4) #should be 5
Definition in file median_search.cpp.
int main | ( | void | ) |
Main function
Definition at line 128 of file median_search.cpp.
int search::median_search::median_of_medians | ( | const std::vector< int > & | A, |
const int & | idx ) |
This function search the element in an array for the given index.
A | array where numbers are saved |
idx | current index in array |
Definition at line 62 of file median_search.cpp.
void test | ( | ) |
Function to test above algorithm
Definition at line 107 of file median_search.cpp.