Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!news.glorb.com!npeer01.iad.highwinds-media.com!news.highwinds-media.com!feed-me.highwinds-media.com!border3.nntp.dca.giganews.com!Xl.tags.giganews.com!border1.nntp.dca.giganews.com!nntp.giganews.com!local2.nntp.dca.giganews.com!nntp.earthlink.com!news.earthlink.com.POSTED!not-for-mail NNTP-Posting-Date: Wed, 01 Aug 2012 11:26:21 -0500 Message-ID: <501958AC.5261@mindspring.com> Date: Wed, 01 Aug 2012 12:26:20 -0400 From: pete Reply-To: pfiland@mindspring.com Organization: PF X-Mailer: Mozilla 3.04Gold (WinNT; I) MIME-Version: 1.0 Newsgroups: comp.programming Subject: Re: problem 2.1.2 from "how to solve it by computer, Dromey" References: <5014B5FE.2FC3@mindspring.com> Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Lines: 86 X-Usenet-Provider: http://www.giganews.com NNTP-Posting-Host: 4.154.221.138 X-Trace: sv3-XXh5XrA57P1Jer3pSiIOdqKY7jKAwfSGeWWfAsdLsLK+Jdj9O2K/G42ZBKaN4/65rzNlGLCTpYWKh/l!kHcLWDLSqSWw7Pi7ck/TErOv7PJ1HoSwdPFpufx3dQVtvjgTwGbwMHFz6LTY4PWrbYtd+2OBv2kk!VkYdoCjUaCE= X-Abuse-and-DMCA-Info: Please be sure to forward a copy of ALL headers X-Abuse-and-DMCA-Info: Otherwise we will be unable to process your complaint properly X-Postfilter: 1.3.40 X-Original-Bytes: 2647 X-Received-Bytes: 2788 Xref: csiph.com comp.programming:2029 pete wrote: > > sathyashrayan wrote: > > > > I am a beginner in learning algo..So please bear with me.. > > > > 2.1.2 Design an algorithm > > that makes following exchanges of 3 varioubles.. > > > > a-->b-->c--| > > ^ | > > ^----------| > > > > So > > a_temp = a; > > b_temp = b; > > c_temp = c; > > > > a=c_temp; > > c=b_temp; > > b=a_temp; > > > > I know this process looks ugly. > > Can anyone suggest a good one so that I could learn. > > temp = c > c = b > b = a > a = temp If you were in a situation where you might not be guaranteed to have a temp variable suitable for the values of the variables in question, but if you had a way to swap values between variables, then something like this would work: SWAP(b, c); SWAP(a, b); In C, that could look like this: /* BEGIN new.c */ #include #define SWAP(X, Y) (swap(&X, &Y, sizeof X)) void swap(void *arg1, void *arg2, size_t size) { unsigned char temp; unsigned char *a1 = arg1; unsigned char *a2 = arg2; while (size-- != 0) { temp = *a1; *a1++ = *a2; *a2++ = temp; } } int main(void) { int a = 1; int b = 2; int c = 3; printf("(a) is %d\n", a); printf("(b) is %d\n", b); printf("(c) is %d\n", c); putchar('\n'); SWAP(b, c); SWAP(a, b); printf("(a) is %d\n", a); printf("(b) is %d\n", b); printf("(c) is %d\n", c); return 0; } /* END new.c */ -- pete