The O (N) algorithm and kmin algorithm of C + + to find median number _c language

Source: Internet
Author: User
Tags assert int size

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.