Reverse Array Elements in C

Reverse Array Elements in C

a tricky method to swap values

Code Snippet / C Notes

2019.11.11

0 #array #C

Inplace swap of values stored at the locations with a bit-level trick:

void inplace_swap(int *x, int *y) {
  *y = *x ^ *y;
  *x = *x ^ *y;
  *y = *x ^ *y;
}

Details of this trick can be found at: In-place Swap, in C.

Then, using the following function to reverse the elements in an array:

void reverse_array(int a[], int cnt) {
  int first, last;
  for (first = 0, last = cnt - 1; first < last; first++, last--) {
    inplace_swap(&a[first], &a[last]);
  }
}

林宏

Frank Lin

Hey, there! This is Frank Lin (@flinhong), one of the 1.4 billion 🇨🇳. This 'inDev. Journal' site holds the exploration of my quirky thoughts and random adventures through life. Hope you enjoy reading and perusing my posts.

YOU MAY ALSO LIKE

HTML 相对路径和绝对路径区别分析

Web Notes

2015.09.26

HTML 相对路径和绝对路径区别分析

HTML 初学者会经常遇到这样一个问题,如何正确引用一个文件。比如,怎样在一个 HTML 网页中引用另外一个 HTML 网页作为超链接(hyperlink),怎样在一个网页中插入一张图片。如果你在引用文件时(如加入超链接,或者插入图片等),使用了错误的文件路径,就会导致引用失效(无法浏览链接文件,或无法显示插入的图片等)。

Using Liquid in Jekyll - Live with Demos

Web Notes

2016.08.20

Using Liquid in Jekyll - Live with Demos

Liquid is a simple templating language that Jekyll uses to process pages on your site. With Liquid you can output an modify variables, have logic statements inside your pages and loop over content.

Self-host comments in Jekyll, powered by Firebase real-time database

Tutorials

2017.03.25

Self-host comments in Jekyll, powered by Firebase real-time database

It's convenient to set up a comment system in Jekyll site with external social comment systems like Disqus or Duoshuo (多说). However, as you all know, Disqus was blocked in China and Duoshuo is going to shutdown. It's the time to rethink about the comment system (although I didn't get too many comments →_→), simple and controllable. And it becomes true with Firebase database.

TRENDING