Programming Algorithm-sorting and splitting code (c)

Source: Internet
Author: User
Sort and split code (c)


Address: http://blog.csdn.net/caroline_wendy


Sort and split, Divides an array,Greater Than k \ Less Than k \ equal to K.

AvailablePartition Function of quick sorting, Processing, put more than K on the left, less than K on the right.

Use a variable recordCenter Position, ThenTime ComplexityIsO (3n/2).


Code:

/** Main. CPP ** created on: 2014.9.18 * Author: Spike * // * eclipse CDT, GCC 4.8.1 */# include <iostream> # include <list> # include <queue> # include <string. h> # include <stdlib. h> using namespace STD; int randominrange (INT min, int max) {return rand () % (max-min + 1) + min;} void swap (int * num1, int * num2) {int TMP = * num1; * num1 = * num2; * num2 = TMP;} int partitionk (INT data [], int length, int K) {If (Data = NULL | Length <= 0) Return-1; int small =-1; int Index = 0; For (Index = 0; index <length; ++ index) {If (data [Index] <k) {small ++; If (small! = Index) Swap (& Data [small], & Data [Index]) ;}} int Pos = ++ small; // record location small = length; Index = 0; for (Index = length-1; index> = Pos; index --) {If (data [Index]> K) {small --; If (small! = Index) Swap (& Data [small], & Data [Index]) ;}} return -- small;} int main (void) {int data [] = {1, 3, 2, 5, 2, 0, 5, 2,-1, 0, 4}; int length = sizeof (data)/sizeof (data [0]); partitionk (data, length, 2); For (INT I = 0; I <length; ++ I) {cout <data [I] <"";} cout <Endl; return 0 ;}

Output:

1 0 -1 0 2 2 2 3 5 5 4 






Programming Algorithm-sorting and splitting code (c)

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.