This article describes the C + + to find the median O (N) algorithm and kmin algorithm, shared for everyone to reference. The specific methods are as follows:
The search algorithm for the median of O (N) time by using the fast sort partition operation is as follows:
#include <iostream> #include <cassert> #include <algorithm> #include <iterator> using namespace
Std
int array[] = {1, 2, 10, 8, 9, 7, 5};
const int size = sizeof array/sizeof *array;
int partition (int *array, int left, int right) {if (array = = NULL) return-1;
int pos = right;
right--;
while (left <= right) {while (Left < POS && Array[left] <= Array[pos]) left++;
while (right >= 0 && array[right] > Array[pos]) right--;
if (left >= right) break;
Swap (Array[left], array[right]);
} swap (Array[left], Array[pos]);
return to left;
int getmidindex (int *array, int size) {if (array = NULL | | size <= 0) return-1;
int left = 0;
int right = size-1;
int midpos = right >> 1;
int index =-1;
while (index!= midpos) {index = partition (array, left, right);
if (Index < Midpos) {left = index + 1;
else if (Index > Midpos) {right = Index-1;
} else {break;
}
} ASSERT (index = = Midpos);
return Array[index];
} void Main () {int value = Getmidindex (array, size);
cout << "Value:" << value << Endl;}
The search Kmin algorithm is as follows:
int findkmin (int *array, int size, int k)
{
if (array = NULL | | size <= 0)
return-1;
int left = 0;
int right = size-1;
int index =-1;
while (index!= k)
{
index = partition (array, left, right);
if (Index < k)
{left
= index + 1;
}
else if (Index > K)
{right
= index-1;
}
Else
{break
;
}
}
ASSERT (index = = k);
return array[index];
}
I hope this article is helpful to the learning of C + + program algorithm design.