# Fall 2001 CSCI 333 Homework 8 Solution

These are solutions to the problems of Homework 8 that were not assigned from the textbook.

## Problem 1

The problem is to use the `qsort` routine to sort 3000 records of the following type:

``````
struct city {
char Name[80] ;
char State[2] ;
}
```
```

First, you need a routine to compare the records. The problem requires us to sort first by city and then by state. The arguments to this routine are of type `void *` as required in the specification of `qsort`. Consequently, we must cast the arguments to type `struct city *` before accessing the fields of the record.

``````
int cityCmp(const void *R1, const void *R2) {
struct city *P1, *P2 ;
int tempCmpRes ;
P1 = (struct city *)R1 ;
P2 = (struct city *)R2 ;
/* Compare the states.  If unequal, return the result of the compare */
if (tempCmpRes = strncmp(P1->State, P2->State, 2))
return tempCmpRes ;
else
return strncmp(P1->Name, P2->Name, 80) ;
}
```
```

Assume `Cities` is our array of 3000 `struct city` records. Now we only need to call `qsort`. Of course, `qsort` expects the array to be passed as a `void *`.

``````
qsort((void *)Cities, 3000, sizeof(struct city), cityCmp) ;
```
```

## Problem 3

The ASCII values for the letters 'U', 'N', 'C', and 'A' are, in hex, `0x55`, `0x4e`, `0x43`, and `0x41`, respectively.

C statement *key h g
initally `0x55` or `'U'` `0x00000000`
`h = (h << 4) + *key++ ;` `0x4e` or `'N'` `0x00000055`
`unsigned long g = h & 0xF0000000L ;` `0x4e` or `'N'` `0x00000055` `0x00000000`
`if (g) h ^= g >> 24 ;` `0x4e` or `'N'` `0x00000055` `0x00000000`
`h &= ~g ;` `0x4e` or `'N'` `0x00000055` `0x00000000`
`h = (h << 4) + *key++ ;` `0x43` or `'C'` `0x0000059e`
`unsigned long g = h & 0xF0000000L ;` `0x43` or `'C'` `0x0000059e` `0x00000000`
`if (g) h ^= g >> 24 ;` `0x43` or `'C'` `0x0000059e` `0x00000000`
`h &= ~g ;` `0x43` or `'C'` `0x0000059e` `0x00000000`
`h = (h << 4) + *key++ ;` `0x41` or `'A'` `0x00005a23`
`unsigned long g = h & 0xF0000000L ;` `0x41` or `'A'` `0x00005a23` `0x00000000`
`if (g) h ^= g >> 24 ;` `0x41` or `'A'` `0x00005a23` `0x00000000`
`h &= ~g ;` `0x41` or `'A'` `0x00005a23` `0x00000000`
`h = (h << 4) + *key++ ;` `0x00` `0x0005a271`
`unsigned long g = h & 0xF0000000L ;` `0x00` `0x0005a271` `0x00000000`
`if (g) h ^= g >> 24 ;` `0x00` `0x0005a271` `0x00000000`
`h &= ~g ;` `0x00` `0x0005a271` `0x00000000`

So, the answer is `0x0005a271`. The problem would have been more interesting had the string had more than eight characters.