473,566 Members | 3,245 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How can I make this code less ugly?

I have written a sorting program, to try to understand how heapsort
works. Unfortunately, considering it's supposed to help my
understanding, one line of it has got very ugly and so I was wondering
if anyone had any advice on how to make it clearer.

The code is C++, but I am rashly cross-posting to comp.lang.c as the
part I am having difficulty with is the same as C and I thought the
peoplr there might also be able to help. You can make it a proper C
program by replacing the definition of n with a #define. I'm aware that
the sort is not actually a heapsort, but I think I know where I'm going
there. I also appreciate that it is only a "toy" program at present and
if I was going to put it to proper use I would be better with a
function pointer for the comparison.

So here is the code:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h// for INT_MAX

const int n = 11;
const int h = (n-1)/2;

typedef int VAL;
const VAL EMPTY = INT_MAX;

/* Special casing would be necessary if n was even. Code also assumes
EMPTY is bigger than real values. */

int main(void) {
int x, y, z, z1, z2;
VAL a[n], b[n], c[n], t;

for (x=0; x < n; x++)
a[x] = rand() % 1000;

printf("Unsorte d:");
for (x=0; x < n; x++)
printf(" %d", a[x]);
printf("\n\n");

/* Put values into b, in such a way that b[x] is always less than or
equal to both b[2x+1] and b[2x+2] (where x < h). This can be done
in O(n log n) and could if necessary be done in place in a. */

for (x = 0; x < n; x++) {
t = a[x];
y = x;
while (y 0 && t < b[z=(y-1)/2]) {
b[y] = b[z];
y = z; }
b[y] = t; }

/* Now pull them out again */

for (x = 0; x < n; x++) {
c[x] = b[0];
y = 0;
while (y < h && (b[z2=2*y+2,z1=2*y +1] < EMPTY || b[z2] < EMPTY)) {
if(b[z1] <= b[z2]) { b[y] = b[z1]; y = z1; }
else { b[y] = b[z2]; y = z2; } }
b[y] = EMPTY; }

printf("Sorted: ");
for (x=0; x < n; x++)
printf(" %d", c[x]);
printf("\n\n");
return 0;
}

The snag is with the while statement which sets up the values of z1 and
z2. My first attempt at the program had:

while (y < h && (b[z1=2*y+1] < EMPTY || b[z2=2*y+2] < EMPTY)) {

which is still somewhat messy, but this had the disadvantage of not
working (the program ran forever). The snag with that version is that,
if b[z1] is not empty, the value of z2 does not get set. Hence I have
changed it to the abomination above.

Can anyone advise how to make it clearer?

Thanks for your help.
Paul.

Jul 10 '06 #1
10 1583

gw****@aol.com wrote:
The code is C++
So here is the code:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h// for INT_MAX
Nope, the code is C.

Jul 10 '06 #2
On Mon, 10 Jul 2006 gw****@aol.com wrote:
I have written a sorting program, to try to understand how heapsort
works. Unfortunately, considering it's supposed to help my
understanding, one line of it has got very ugly and so I was wondering
if anyone had any advice on how to make it clearer.

[snip]

y = 0;
while (y < h && (b[z2=2*y+2,z1=2*y +1] < EMPTY || b[z2] < EMPTY)) {
How about this:

for (y = 0, z1 = 1, z2 = 2;
y < h && (b[z1] < EMPTY || b[z2] < EMPTY);
z1 = 2 * y + 1, z2 = 2 * y + 2) {

Tak-Shing
Jul 10 '06 #3
Noah Roberts wrote:
gw****@aol.com wrote:
>The code is C++
>So here is the code:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h// for INT_MAX

Nope, the code is C.
The code you quoted is valid in both C and C++.

The code you snipped is not C:
>const int n = 11;
const int h = (n-1)/2;
The initialiser for h is not a constant expression in C.

--
Simon.
Jul 11 '06 #4
gw****@aol.com wrote:
while (y < h && (b[z2=2*y+2,z1=2*y +1] < EMPTY || b[z2] < EMPTY)) {
if(b[z1] <= b[z2]) { b[y] = b[z1]; y = z1; }
else { b[y] = b[z2]; y = z2; } }
while (y < h && (z1=2*y+1, z2=2*y+2, b[z1] < EMPTY || b[z2] < EMPTY))
if (b[z1] <= b[z2]) b[y] = b[z1], y = z1;
else b[y] = b[z2], y = z2;

or

while (y < h && (z = 2*y, b[z+1] < EMPTY || b[z+2] < EMPTY))
if (b[z+1] <= b[z+2]) b[y] = b[z+1], y = z+1;
else b[y] = b[z+2], y = z+2;

or

while (y < h && (b[2*y+1] < EMPTY || b[2*y+2] < EMPTY))
z = 2*y + (b[2*y+1] <= b[2*y+2] ? 1 : 2), b[y] = b[z], y = z;

or

while (y < h && (z = 2*y, b[z+1] < EMPTY || b[z+2] < EMPTY))
z += b[z+1] <= b[z+2] ? 1 : 2, b[y] = b[z], y = z;

--
Dietmar
Jul 13 '06 #5

Dietmar Schindler wrote:
gw****@aol.com wrote:
while (y < h && (b[z2=2*y+2,z1=2*y +1] < EMPTY || b[z2] < EMPTY)) {
if(b[z1] <= b[z2]) { b[y] = b[z1]; y = z1; }
else { b[y] = b[z2]; y = z2; } }

while (y < h && (z1=2*y+1, z2=2*y+2, b[z1] < EMPTY || b[z2] < EMPTY))
if (b[z1] <= b[z2]) b[y] = b[z1], y = z1;
else b[y] = b[z2], y = z2;

or

while (y < h && (z = 2*y, b[z+1] < EMPTY || b[z+2] < EMPTY))
if (b[z+1] <= b[z+2]) b[y] = b[z+1], y = z+1;
else b[y] = b[z+2], y = z+2;

or

while (y < h && (b[2*y+1] < EMPTY || b[2*y+2] < EMPTY))
z = 2*y + (b[2*y+1] <= b[2*y+2] ? 1 : 2), b[y] = b[z], y = z;

or

while (y < h && (z = 2*y, b[z+1] < EMPTY || b[z+2] < EMPTY))
z += b[z+1] <= b[z+2] ? 1 : 2, b[y] = b[z], y = z;
Thanks for your suggestions. I think the first option may be the one to
go for - setting both the values of z1 and z2 before mentioning b.
Either that, or miss out the z's completely - more like your second
option.

Jul 13 '06 #6
gw****@aol.com wrote:
Dietmar Schindler wrote:
>gw****@aol.com wrote:
>> while (y < h && (b[z2=2*y+2,z1=2*y +1] < EMPTY || b[z2] < EMPTY)) {
if(b[z1] <= b[z2]) { b[y] = b[z1]; y = z1; }
else { b[y] = b[z2]; y = z2; } }
while (y < h && (z1=2*y+1, z2=2*y+2, b[z1] < EMPTY || b[z2] < EMPTY))
if (b[z1] <= b[z2]) b[y] = b[z1], y = z1;
else b[y] = b[z2], y = z2;

or

while (y < h && (z = 2*y, b[z+1] < EMPTY || b[z+2] < EMPTY))
if (b[z+1] <= b[z+2]) b[y] = b[z+1], y = z+1;
else b[y] = b[z+2], y = z+2;

or

while (y < h && (b[2*y+1] < EMPTY || b[2*y+2] < EMPTY))
z = 2*y + (b[2*y+1] <= b[2*y+2] ? 1 : 2), b[y] = b[z], y = z;

or

while (y < h && (z = 2*y, b[z+1] < EMPTY || b[z+2] < EMPTY))
z += b[z+1] <= b[z+2] ? 1 : 2, b[y] = b[z], y = z;

Thanks for your suggestions. I think the first option may be the one to
go for - setting both the values of z1 and z2 before mentioning b.
Either that, or miss out the z's completely - more like your second
option.
How about moving the test into a separate function as well

while (myCondition())
{
// option 1 code.
}
Jul 13 '06 #7

Simon Biber wrote:
Noah Roberts wrote:
gw****@aol.com wrote:
The code is C++
So here is the code:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h// for INT_MAX
Nope, the code is C.

The code you quoted is valid in both C and C++.
Those headers don't exist in C++.

Jul 14 '06 #8
* Noah Roberts:
Simon Biber wrote:
>Noah Roberts wrote:
>>gw****@aol.com wrote:
The code is C++
So here is the code:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h// for INT_MAX
Nope, the code is C.
The code you quoted is valid in both C and C++.

Those headers don't exist in C++.
They do exist in C++.

The code is pure C, specifically C99, with no trace of C++; it does
contain an error (the const initializer mentioned elsethread), but that
does not make it C++.

Cross-posting to clc and clc++ is evil.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 14 '06 #9
Noah Roberts wrote:
Simon Biber wrote:
>Noah Roberts wrote:
>>gw****@aol.com wrote:
The code is C++
So here is the code:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h// for INT_MAX
Nope, the code is C.
The code you quoted is valid in both C and C++.

Those headers don't exist in C++.
Yes they do. They are still valid in C++.

C++ doesn't force existing code to change to the new and preferred
<cstdiostyle header names.

--
Simon.
Jul 14 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
2177
by: Pedro Graca | last post by:
<?php function ugly_array() { return array(1, 2, 3, 4, 5); } $arr = ugly_array(); echo $arr; ?> not so ugly :) now ... I want to get rid of the $arr temporary variable.
25
6601
by: Johan Bergman | last post by:
Hi, Maybe someone can help me to optimize this C/C++ implementation of a FIR filter (although I realize that I should probably consider an FFT approach instead.) The example below calculates the output signal for 10000 lags from an FIR filter with 10000 taps. The input signal and the filter coefficients is just rubbish in this example....
7
4816
by: Skybuck Flying | last post by:
Hi, if (__builtin_expect (!buffer->__init, 0)) { buffer->__a = 0x5deece66dull; buffer->__c = 0xb; buffer->__init = 1; } I am using visual c 6 and this code doesn't compile, it's probably not
26
1943
by: William L. Bahn | last post by:
Am I invoking any undefined behavior in the following program? /* Function to print out the bit pattern stored in a variable regardless of type */ #include <limits.h> /* CHAR_BIT */ #include <stdio.h> /* putc() */ void printbits(unsigned char *p, int bytes);
14
1936
by: Steven D'Aprano | last post by:
I came across an interesting (as in the Chinese curse) problem today. I had to modify a piece of code using generator expressions written with Python 2.4 in mind to run under version 2.3, but I wanted the code to continue to use the generator expression if possible. My first approach was to use a try...except block to test for generator...
60
5003
by: Dave | last post by:
I'm never quite sure whether to use "this." or not when referring to fields or properties in the same class. It obviously works just fine without it but sometimes I wonder if using this. consistently may make the code easier to understand for someone else, etc. Using "this." makes it immediately clear, for example, that the variable being...
9
1583
by: Joel Hedlund | last post by:
Hi! I need some input on my use of metaclasses since I'm not sure I'm using them in a pythonic and graceful manner. I'm very grateful for any tips, pointers and RTFMs I can get from you guys. Below, you'll find some background info and an executable code example. In the code example I have two ways of doing the same thing. The problem...
10
301
by: gw7rib | last post by:
I have written a sorting program, to try to understand how heapsort works. Unfortunately, considering it's supposed to help my understanding, one line of it has got very ugly and so I was wondering if anyone had any advice on how to make it clearer. The code is C++, but I am rashly cross-posting to comp.lang.c as the part I am having...
18
15108
by: lovecreatesbea... | last post by:
Isn't code at line 2 correct? a.c:2: warning: suggest parentheses around && within || int isleap(int year){ if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) /*line 2*/ return 1; return 0; }
52
3064
by: Paul McGuire | last post by:
I'm starting a new thread for this topic, so as not to hijack the one started by Steve Howell's excellent post titled "ten small Python programs". In that thread, there was a suggestion that these examples should conform to PEP-8's style recommendations, including use of lower_case_with_underscores style for function names. I raised some...
0
7673
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7584
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7893
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8109
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7953
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5485
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3643
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2085
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
926
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.