Adjust the element position in the given integer array so that the odd number is in the front of the even number.

Source: Internet
Author: User

The method is to use two pointers. The first pointer points to the beginning and increments backward. The second Pointer Points to the end and increments forward.


# Include <stdio. h> # include <stdlib. h> void alter (int data [], int length) {int * head = data, * tail = data + length-1, temp; while (head <tail) {while (head <tail & * head % 2) head ++; // you must also judge head <tail, because the head increment may exceed the value of tail while (head <tail &&! (* Tail % 2) tail --; if (head <tail) {temp = * head; * head = * tail; * tail = temp ;}} void main () {int I, data [10] = {1, 2, 3, 4, 5, 8, 7, 6, 5, 1}; alter (data, 10); for (I = 0; I <10; I ++) printf ("% d \ t", data [I]); getch ();}

The sword means that there is also a good way of writing extensibility on the offer, which is to pass a function pointer to the alter function to determine whether to move.

This decoupling method improves code reusability.

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.