473,549 Members | 2,366 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

problem with array

Hi all!

Still working on this program!

Just to recap, I am writing a program to sort an array with four
different sort algorythms.
I am having a little trouble at the moment though!

Now, I am trying to calculate, with each sort, how many times during
the sort the array elements are compared and swapped.
I am coping the original array into a temp (iTmp) array to be sorted.
Then, I am using a menu to call each Sort function where I am passing
in iTmp plus the array's
size to be sorted.

-----------------------------------------
while ((iMenuChoice = menu()) != QUIT) // print menu & loop until
QUIT
switch( iMenuChoice ) {
case 1: // user enters 1: selection sort....
selectionSort( iTmpArr, SIZE );
break;
Nov 13 '05 #1
3 2463
ritchie wrote:

Hi all!

Still working on this program!

Just to recap, I am writing a program to sort an array with four
different sort algorythms.
I am having a little trouble at the moment though!

Now, I am trying to calculate, with each sort, how many times during
the sort the array elements are compared and swapped. The problem though, is that each time I call the next sort from the
menu (while still in SWITCH statement until QUIT ) the comparisons and
swaps are being incorrectly calculated.

I know this is because the functions are getting the same array.
I am coping the original array into iTmp BEFORE the SWITCH which is
within the while loop.
Is there anywhere else I should be copying the arrays?
I tried to copy the arrays before each function call in the SWITCH but
this didn't work.


Post the whole program.

--
pete
Nov 13 '05 #2


ritchie wrote:
Hi all!

Still working on this program!

Just to recap, I am writing a program to sort an array with four
different sort algorythms.
I am having a little trouble at the moment though!

Now, I am trying to calculate, with each sort, how many times during
the sort the array elements are compared and swapped.
I am coping the original array into a temp (iTmp) array to be sorted.
Then, I am using a menu to call each Sort function where I am passing
in iTmp plus the array's
size to be sorted.

-----------------------------------------
while ((iMenuChoice = menu()) != QUIT) // print menu & loop until
QUIT
switch( iMenuChoice ) {
case 1: // user enters 1: selection sort....
selectionSort( iTmpArr, SIZE );
break;
.
.
.
}
}
-----------------------------------------------
Within each sort function I call 'displaySorted' , where I pass in
iTmp(copied array), array size, comparisons & swaps (calculated from
functions).
-------------------------------------
void displaySorted( int iTmpArr[], int iMax, int iComparison, int
iSwaps )
{
int i;

printf("Your Sorted Array:\n");
for(i=0; i<=MAX-1; i++ )
printf("%4d", iTmpArr[i]);
printf("\n");

printf( "Comparison s: %d \n", iComparison );
printf( "Swaps: %d \n", iSwaps );
-----------------------------------------------------+

The problem though, is that each time I call the next sort from the
menu (while still in SWITCH statement until QUIT ) the comparisons and
swaps are being incorrectly calculated.

I know this is because the functions are getting the same array.
I am coping the original array into iTmp BEFORE the SWITCH which is
within the while loop.
I don't believe it would matter, but I would to the array
copying and printing in the while loop.

Is there anywhere else I should be copying the arrays?
I tried to copy the arrays before each function call in the SWITCH but
this didn't work.

Anyone have any ideas?


I assume that when you say it doesn't work that the problem is
incorrect values in the number of comparisons and number of swaps.
If so, you should look carefully at how you define and use these
variables in the sort and/or comparision functions. Here is
an example, untested, of using these variables in a bubblesort and
selectionsort function.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void PointertoOrigin ( int *a, int **pa, size_t);
void bubblesort(void *base, size_t n, size_t size,
int (*cmp)(const void *el1, const void *el2),
size_t *comparisons, size_t *swaps);
void selectionsort(v oid *base, size_t n, size_t size,
int (*cmp)(const void *el1, const void *el2),
size_t *comparisons, size_t *swaps);
void swap(void *e1, void *e2, size_t size);
int cmp(const void *e1, const void *e2);
void PrintArrays(int *a, int **pa,size_t n);
int menuselection(v oid);

int main(void)
{
int array[10] = {4,3,6,1,8,10,2 ,5,7,9};
int *parray[10];
size_t comparisons, swaps;
int choice;
while(1)
{
PointertoOrigin (array,parray,1 0);
choice = menuselection() ;
if(choice == 'q' || choice == 'Q') break;
if(choice < '1' || choice > '2')
{
puts("Invalid entry. Try again");
continue;
}
switch(choice)
{
case '1': bubblesort(parr ay,10, sizeof(*parray) ,
cmp, &comparisons,&s waps);
break;
case '2': selectionsort(p array,10, sizeof(*parray) ,
cmp, &comparisons,&s waps);
break;
}
PrintArrays(arr ay,parray,10);
printf("Number Comparisons: %u\n"
"Number swaps: %u\n\n\n",
comparisons, swaps);
}
return 0;
}
void PointertoOrigin ( int *a, int **pa, size_t n)
{
size_t i;

for(i = 0; i < n;i++)
pa[i] = &a[i];
return;
}

void bubblesort(void *base, size_t n, size_t size,
int (*cmp)(const void *el1, const void *el2),
size_t *comparisons, size_t *swaps)
{
size_t i, sorted = 0;
char *p = (char *) base;

*comparisons = *swaps = 0;
while(!sorted)
{
sorted = 1;
for(i = 0;i < n-1; i++)
{
(*comparisons)+ +; /* increment the comparison variable */
if(cmp(p+(i*siz e),p+((i+1)*siz e))>0)
{
(*swaps)++; /* increment the swap variable */
swap(p+(i*size) ,p+((i+1)*size) ,size);
sorted = 0;
}
}
}
}

void swap(void *e1, void *e2, size_t size)
{
char buf[256], *p1 = (char *)e1, *p2 = (char *)e2;
size_t ms;

for(ms = size; 0< ms; )
{
size_t m = ms < sizeof(buf)?ms: sizeof(buf);
memcpy(buf,p1,m );
memcpy(p1,p2,m) ;
memcpy(p2,buf,m );
ms -= m, p1+=m, p2+=m;
}
return;
}

int cmp(const void *e1, const void *e2)
{
int *i1 = *(int **)e1, *i2 = *(int **)e2;

return (*i1<*i2)?-1:(*i1!=*i2);
}

void PrintArrays( int *a, int **pa, size_t n)
{
size_t i;

printf("The unsorted array: ");
for(i = 0; i < n;i++) printf("%d ",a[i]);
printf("\nThe sorted pointers : ");
for(i = 0; i < n;i++) printf("%d ", *pa[i]);
putchar('\n');
return;
}

void selectionsort(v oid *base, size_t n, size_t size,
int (*cmp)(const void *el1, const void *el2),
size_t *comparisons, size_t *swaps)
{
size_t position, smallest_idx,i;
char *p = (char *)base;

*comparisons = *swaps = 0;
for(position = 0; position < n-1; position++)
{
smallest_idx = position;
for(i = position+1;i < n; i++)
{
(*comparisons)+ +;
if(cmp(p+(i*siz e),p+(smallest_ idx*size)) < 0)
smallest_idx = i;
}
if(smallest_idx != position)
{
(*swaps)++;
swap(p+(smalles t_idx*size),p+( position*size), size);
}
}
}

int menuselection(v oid)
{
char choice[16];

printf("\nSorti ng test\n\t1) BubbleSort\n\t"
"2) SelectionSort\n Enter the number"
"('q' to quit): ");
fflush(stdout);
fgets(choice,si zeof choice, stdin);
return (int)*choice;
}

--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapi dsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 13 '05 #3
buddy!

u need to chek wether the array is sorted correctly or not...if it is
being sorted correctly then the problem lies in the calulation of the
variables..u did not specify wether the actual figure is smaller than
or larger than the calculated figure..if it is smaller then the
problem could be due to initializing of the variables...it may be
adding up previous results...if it is smaller then the loop is not set
right for calculation...c hek it closely...it depends a lot on where
exactly u are incrementing the comparision and swap variables..
hope it helps...
do let me know if any more input is required..
u can send in the omplete code to hp*****@vcustom er.net
if u want me to take a look at it
Nov 13 '05 #4

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

Similar topics

4
3820
by: JesusFreak | last post by:
From: us_traveller@yahoo.com (JesusFreak) Newsgroups: microsoft.public.scripting.jscript Subject: toolbar script problem NNTP-Posting-Host: 192.92.126.136 Recently, I downloaded the following beautiful script "http://javascript.internet.com/navigation/toolbar-menu.html". It works like a charm. I made my webpage in frames, where the...
0
285
by: crawlerxp | last post by:
This is the problem: I do not get the output I need when encoding and decoding data using rijndael alghoritm. Look at the code and see what the problem is actually: Please paste this code into your Visual Studio and compile it + run it; so you can see what the actual problem is. Thanks. code:
8
15348
by: Brady | last post by:
Hi, I'm having a problem reading and writing to a file. What I'm trying to do is read a file, modify the portion of the file that I just read, and then write the modified data back to the same location in the file. What is happening, is I can read the file, either in entirety or only part of it. And no matter what I try setting the...
8
3356
by: mytfein | last post by:
Hi Everyone, Background: Another department intends to ftp a .txt file from the mainframe, for me to process. The objective is to write a vb script that would be scheduled to run daily to process this .txt file. Goal: I am working on a vba script to:
8
10698
by: intrepid_dw | last post by:
Hello, all. I've created a C# dll that contains, among other things, two functions dealing with byte arrays. The first is a function that returns a byte array, and the other is intended to receive a byte array as one of its parameters. The project is marked for COM interop, and that all proceeds normally. When I reference the type...
4
11215
by: daroman | last post by:
Hi Guys, i've problem with my small C++ programm. I've just small template class which represetns a array, everything works fine up to combination with std::string. I did tried it with M$ VC++ and with GCC (Cygwin and Linux) and my problem is when i try do this int main(int argc, char **argv) { array<std::stringa(10); a = "Huhuhu"; <---...
5
2550
by: weidongtom | last post by:
Hi, I tried to implement the Universal Machine as described in http://www.boundvariable.org/task.shtml, and I managed to get one implemented (After looking at what other's have done.) But when I use to run a UM program, I kept on getting error messages. I have used someone else's implementation and it runs fine. I have compared my code...
9
2488
by: weidongtom | last post by:
Hi, I've written the code that follows, and I use the function add_word(), it seems to work fine *before* increase_arrays() is called that uses realloc() to allocate more memory to words. But *after* calling increase_arrays(), I received segmentation fault. I tried to step it through gdb, and I found out that after calling...
3
6336
by: raylopez99 | last post by:
Below is my problem. I've narrowed it down to one thing: my unfamiliarity on how class instances are instantiated in an array. This is because the "un-array" / "non-array" version of the program works fine (see below). So what is the problem? I get a null reference on the line below at *!&!* "Unhandled Exception:...
25
2330
by: biplab | last post by:
Hi all, I am using TC 3.0..there if I declare a integer array with dimension 162*219...an error msg saying that too long array is shown....what should I do to recover from this problem???
0
7546
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
7740
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. ...
1
7503
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7830
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...
0
6071
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3517
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...
0
3496
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1962
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
1
1082
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.