In-place inverse algorithm of sequential table

Source: Internet
Author: User

1#include <stdio.h>2 #defineMAX 103typedefintElementType;4 intLength=0;5 intvalue;6typedefstruct {7 ElementType i;8     intlength;9 ElementType Data[max];Ten }sorder; One intMain () { A Sorder L; -     //plug data into the order table -      for(intI=0; i<max;i++){ thel.data[i]=i+1; -l.length++; -     } -     //The main algorithm code, to Exchange +       for(intI=0;i< (l.length)/2; i++){ -Value=L.data[i]; +l.data[i]=l.data[l.length-i-1]; Al.data[l.length-i-1]=value; at     } -     //the output is in reverse order -      for(intI=0; i<max;i++){ -printf"%d", L.data[i]); -     } -}

Q: Design an efficient algorithm that will reverse all elements of the sequential table, requiring the spatial complexity of the algorithm to be O (1);

A: The complexity of this algorithm corresponds to the second problem in the first chapter of the benevolent exercise, the main idea of the algorithm is as follows:

(1) Scan the first half of the order table element, for L.data[i] (I is greater than or equal to 0 less than l.length-1)

(2) Exchange The remaining second half of the corresponding element l.data[l.length-i+1].

Summary: In fact, the main reason is the understanding of the second for Loop, which is also the core code, with the help of the value of the auxiliary variable for an exchange, which is very common in many places.

In-place inverse algorithm of sequential table

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.