How the chaotic array of integers is implemented left is all odd-numbered right all are even (numbers do not require sorting)

Source: Internet
Author: User
Tags array length

Today, colleagues estimated that the egg pain, suddenly began to recall the interview process quilt cover to some of the interview problems, there are logic, there are algorithms, and then to test my ideas, the title of the algorithm is one of the interview algorithm he met.

Get the first feeling of the topic, is LINQ, LINQ is Bad, the problem of this algorithm directly to LINQ you tease who, tidy up the idea, Tu, the title only requires the left odd, the right even, does not require the two sides of the integer also to be ordered separately, that algorithm thinking so determined, by index from low to high cycle , if an even number is encountered, the reverse loop within the loop, that is, from the high to low loop to find the odd number to achieve the position of alternating, the algorithm is implemented as follows:

static void Setleftsingleandrightdoubleone (int[] arr) {    int num = 0;    var previndex = arr. Length-1;    for (var i = 0; I <= previndex; i++)    {        if (Arr[i]% 2 = 0)        {//even for             (var j = Previndex; j > i; j-- )            {                num++;                If (Arr[j]% 2! = 0)                {                    //odd                    var b = arr[i];                    Previndex = j-1;//The current position has been replaced with even, so the index of the set value can be reduced by one                    arr[i] = arr[j];                    ARR[J] = b;                    Break        ;        }}} else        {            num++;            Odd            continue;        }    }    Console.WriteLine ("One RUN NUMS:" + num);}
I think the algorithm is not a problem, the time complexity should be f (n) =n-1, but the actual operation, but found that occasionally appearnumber of cycles higher than array lengthPhenomenon, what is this for? Because the problem is in the reverse loop, if the reverse loop to I, can not find the odd, then there will be no previndex assignment, the outer loop will continue to go on, and then there will be more cycles than the length of the array, fix the code, increase the judgment stop flag bit:
static void Setleftsingleandrightdoubleone (int[] arr) {int num = 0; var previndex = arr.    Length-1; for (var i = 0; I <= previndex; i++) {if (arr[i] 2 = = 0) {//even bool stop = false;//Stop flag                Bit for (var j = Previndex; j > i; j--) {num++;                    If (Arr[j]% 2! = 0) {//odd var B = arr[i];                    Previndex = j-1;//The current position has been replaced with even, so the index of the set value can be reduced by one arr[i] = arr[j];                    ARR[J] = b;                Break } stop = j = i + 1;//One more step assignment} if (stop)//Although one more step to judge, but the number of cycles has decreased {//Because the reverse traversal has been traversed to            The previous bit of I, so you can stop traversing the break;            }} else {num++;        Odd continue; }}//console.writeline ("One RUN NUMS:" + num);} 
OK, the algorithm has been implemented, and then get the implementation of colleagues, the general idea of the same, are left and right to traverse the alternate, the specific following:
static void Setleftsingleandrightdoubletwo (int[] arr) {    int left = 0;    int right = arr. Length-1;    int num = 0;    while (left < right)    {        num++;        BOOL leftdouble = Arr[left]% 2 = = 0;//Determine if the left is even        bool rightsingle = arr[right]% 2! = 0;//Judging right is not odd        if (!leftdoubl e)        {            left++;        }        if (!rightsingle)        {            right--;        }        if (leftdouble && rightsingle)        {            int t = arr[left];            Arr[left] = Arr[right];            Arr[right] = t;            left++;            right--;        }    }    Console.WriteLine ("Both RUN NUMS:" + num);}
Compared with the implementation, each cycle will be low to find two positions, and determine whether can be replaced, because each cycle is judged high and low two positions, so the time complexity is lower than the realization of a

Finally, the specific test code, the test results more accurate, each implementation is executed 10 times

Stopwatch watch= new Stopwatch (); for (var i = 0; i <; i++) {    Console.WriteLine ("*******************************") );    Console.WriteLine ("Run the" + (i + 1) + "St Time");    var tmp = Enumerable.range (1, 50/*00000*/). (_ = = Guid.NewGuid ()). Skip (30). ToArray ();    arr = enumerable.repeat<int> (1, 50). ToArray ();    arr = new INT[50];    var arr1 = tmp. ToArray ();    var arr2 = tmp. ToArray ();    Watch. Reset ();    Watch. Start ();    Setleftsingleandrightdoubleone (arr1);    Watch. Stop ();    Console.WriteLine ("One MS:" + watch.) Elapsedmilliseconds);    Console.WriteLine (String. Join (",", arr1));    Watch. Reset ();    Watch. Start ();    Setleftsingleandrightdoubletwo (ARR2);    Watch. Stop ();    Console.WriteLine ("Both MS:" + watch.) Elapsedmilliseconds);    Console.WriteLine (String. Join (",", arr2));}
Finally, respectively, according to the correctness and execution time of two graphs, the correctness of both the same, implementation time to achieve two is better than the realization of a

Correctness

Execution time

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

How the chaotic array of integers is implemented left is all odd-numbered right all are even (numbers do not require sorting)

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.