GIDForums  

Go Back   GIDForums > Computer Programming Forums > C Programming Language
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 23-Oct-2004, 01:48
doc_watson2007 doc_watson2007 is offline
New Member
 
Join Date: Oct 2004
Posts: 7
doc_watson2007 is on a distinguished road
Unhappy

Sorting arrays need help


I am tring to write a program that implements this sort.
Here is the heart of a simple transpsition sort. What are I doing wrong?
********************
CPP / C++ / C Code:
for (i = 0; i < size; ++i)
 for (j = i + 1; j < size; ++j)
    if (arr[i] > arr[j])
       swap(&arr[i], &arr[j]);
********************
thanks for any assistance
USN

CPP / C++ / C Code:
#include <stdio.h>

void swap(int *,int *);

int main(void)

{

int arr[] = { 7, 3, 66, 3, -5, 22, -77, 2} ;
int i, j;


for ( i = 0 ; i < 8; ++i )
	printf("%d ", arr[i]);
	printf("\n");

{

for ( j = i + 1; j < 7; ++j)

	/* Compare Numbers */

if (arr[i] > arr[j])


	/* Display sorted list */

void swap(&arr[i], &arr[j]);

		printf("%d ", arr[j]);
		printf("\n");

return 0;
}
}

/*Unordered data 7 3 66 3 -5 22 -77 2
First pass -77 7 3 66 3 -5 22 2
Second pass -77 -5 7 3 66 3 2 22
Third pass -77 -5 2 7 3 66 3 22
Fourth pass -77 -5 2 3 7 3 66 22
Fifth pass -77 -5 2 3 3 7 22 66
Sixth pass -77 -5 2 3 3 7 22 66
Seventh pass -77 -5 2 3 3 7 22 66 */
Last edited by dsmith : 23-Oct-2004 at 06:58. Reason: Please use [c] & [/c] for syntax highlighting
  #2  
Old 23-Oct-2004, 07:14
dsmith's Avatar
dsmith dsmith is offline
Senior Member
 
Join Date: Jan 2004
Location: Utah, USA
Posts: 1,351
dsmith is a glorious beacon of lightdsmith is a glorious beacon of lightdsmith is a glorious beacon of lightdsmith is a glorious beacon of lightdsmith is a glorious beacon of light
Hi doc_watson2007. Welcome to GIDForums.

There are several problems that I see with your program, but probably the most noticeable is the formatting.

The basic structure of your program should be grouped more like:
CPP / C++ / C Code:
  for ( i = 0 ; i < 8; ++i ){     //Notice the beginning bracket here
    printf("%d ", arr[i]);
    printf("\n");
    for ( j = i + 1; j < 7; ++j){   //Again a beginning bracket
      /* Compare Numbers */
      if (arr[i] > arr[j])   //No bracket needed as only a single command follows.
        swap(&arr[i], &arr[j]);   //You need to write this function.
    }
  }
  return 0;  //Should not be inside the for loop.
}

Notice that the indenting helps to identify which code should be in which loop.

Your print statements are also slightly misplaced I believe. You should sort the entire structure as shown above and then do a completely new loop which prints the entire array.

Also, you need to write the swap function. The basis of which is:
CPP / C++ / C Code:
  temp = a;
  a = b;
  b = temp;

HTH.
  #3  
Old 23-Oct-2004, 13:23
doc_watson2007 doc_watson2007 is offline
New Member
 
Join Date: Oct 2004
Posts: 7
doc_watson2007 is on a distinguished road

sorting arr


Quote:
Originally Posted by dsmith
Hi doc_watson2007. Welcome to GIDForums.

There are several problems that I see with your program, but probably the most noticeable is the formatting.

The basic structure of your program should be grouped more like:
CPP / C++ / C Code:
  for ( i = 0 ; i < 8; ++i ){     //Notice the beginning bracket here
    printf("%d ", arr[i]);
    printf("\n");
    for ( j = i + 1; j < 7; ++j){   //Again a beginning bracket
      /* Compare Numbers */
      if (arr[i] > arr[j])   //No bracket needed as only a single command follows.
        swap(&arr[i], &arr[j]);   //You need to write this function.
    }
  }
  return 0;  //Should not be inside the for loop.
}

Notice that the indenting helps to identify which code should be in which loop.

Your print statements are also slightly misplaced I believe. You should sort the entire structure as shown above and then do a completely new loop which prints the entire array.

Also, you need to write the swap function. The basis of which is:
CPP / C++ / C Code:
  temp = a;
  a = b;
  b = temp;

HTH.
Thanks.
Now I am getting a undef ref for swap(&arr[i], &arr[j]);

/* Compare Numbers */

if (arr[i] > arr[j])
swap(&arr[i], &arr[j]);

}
}
void swap(int *, int *);

{
int tmp;

tmp = i;
i = j;
j = tmp;
}

return 0;
}
  #4  
Old 23-Oct-2004, 14:49
nkhambal nkhambal is offline
Regular Member
 
Join Date: Jul 2004
Location: CA USA
Posts: 313
nkhambal is a jewel in the roughnkhambal is a jewel in the rough
function definition is problem. Are you defining your swap function code inside main() ? Is yes, then you can not do that in C. You have to move the function code outside main() either before or after. Secondly, You are referencing i and j inside swap function without declaring them. Also, i & j are pointers variables and not regular variables. So you can not use

CPP / C++ / C Code:
tmp=i;
i = j;
j = tmp;


it should be

CPP / C++ / C Code:
void swap(int *i, int *j)         //removed the ; here
{
int tmp;

tmp = *i;
*i = *j;
*j = tmp;
}
 

In case you are defining your swap function code after main(). To be able to compile without errors, You need to prototype your swap function before main().Following should be your program structure.

CPP / C++ / C Code:
#include<stdio.h>

void swap(int *, int *);

main()
{

Your main fuction code...

}

swap (int *i, int *j)
{

swap function code.

}


Use code tags when you are posting code.
  #5  
Old 01-Nov-2004, 01:02
doc_watson2007 doc_watson2007 is offline
New Member
 
Join Date: Oct 2004
Posts: 7
doc_watson2007 is on a distinguished road
Talking

sorting arrays


Quote:
Originally Posted by nkhambal
function definition is problem. Are you defining your swap function code inside main() ? Is yes, then you can not do that in C. You have to move the function code outside main() either before or after. Secondly, You are referencing i and j inside swap function without declaring them. Also, i & j are pointers variables and not regular variables. So you can not use

CPP / C++ / C Code:
tmp=i;
i = j;
j = tmp;


it should be

CPP / C++ / C Code:
void swap(int *i, int *j)         //removed the ; here
{
int tmp;

tmp = *i;
*i = *j;
*j = tmp;
}
 

In case you are defining your swap function code after main(). To be able to compile without errors, You need to prototype your swap function before main().Following should be your program structure.

CPP / C++ / C Code:
#include<stdio.h>

void swap(int *, int *);

main()
{

Your main fuction code...

}

swap (int *i, int *j)
{

swap function code.

}


Use code tags when you are posting code.

Thanks . This is what I have so far still head banging.
CPP / C++ / C Code:
#include <stdio.h>

void swap(int *, int *);

int main(void)
{

/* main function code... */

int arr[] = {7, 3, 66, 3, -5, 22, -77, 2};

int i, j;

printf ("\nArray Unordered data:\n");

	for (i = 0; i < 8; ++i)
	
	 printf("%d ", arr[i]);
	  printf("\n\n");

	   for ( i = 0; i < 8-1; ++i )
			for ( j = 1; j < 8-i; ++j )
			printf("%d ", arr[j]);
			printf("\n");

			  if ( arr[i-1] > arr[j] )
				 swap( arr[i-1], arr[j] );
}

/* swap function code. */

void swap(int *i,int *j)

{
int tmp;

tmp = i;
i = j;
j = tmp;
}
Last edited by dsmith : 01-Nov-2004 at 07:11. Reason: Please use [c] & [/c] for syntax highlighting
  #6  
Old 01-Nov-2004, 07:21
dsmith's Avatar
dsmith dsmith is offline
Senior Member
 
Join Date: Jan 2004
Location: Utah, USA
Posts: 1,351
dsmith is a glorious beacon of lightdsmith is a glorious beacon of lightdsmith is a glorious beacon of lightdsmith is a glorious beacon of lightdsmith is a glorious beacon of light
Hi doc_watson2007. Please, please, please use [c] & [/c], when you post C (or C++) code to this forum. Also, I think that this is a must read for proper formatting. Indentation and the such may seem like a little thing, but it is extremely important to readability and will help you catch errors in your code.

The problem with your code is that you keep switching between a swap function that takes two integer pointers and a swap function that takes two ingegers. Right now, you are passing the integers, but your function is looking for pointers. You must pass by pointer, in order for your swap function to act upon the actual values and not just a copy of the values. Therefore, this line should be changed to pass an address like you originally had:

CPP / C++ / C Code:
swap( &arr[i-1], &arr[j] );

Your swap function is correct in header definition, but remember, since you are using pointers to integers, you need to use * notation to specify the value of the what the pointer points to. Check out the differences between your swap function and nkhambal's swap function. Hint: his is correct.

Good luck!
[
  #7  
Old 01-Nov-2004, 14:46
nkhambal nkhambal is offline
Regular Member
 
Join Date: Jul 2004
Location: CA USA
Posts: 313
nkhambal is a jewel in the roughnkhambal is a jewel in the rough
Another problem with your program is the for loops you are using for sorting the array. You are not using { } brackets after each "for" statment. If you do not use {} brackets after any of your loop conditions, only the statment next to your loop condition will be executed.

Following lines of code
CPP / C++ / C Code:
for ( i = 0; i < 8-1; ++i )
      for ( j = 1; j < 8-i; ++j )
      printf("%d ", arr[j]);
      printf("\n");

        if ( arr[i-1] > arr[j] )
            swap( arr[i-1], arr[j] );

Will effectively only execute first printf in the inner for loop. You need to use {} properly in your loops to get the required results.

Also, there is a problem with the sort logic in your for loops. It should be.

CPP / C++ / C Code:
for ( i = 0; i < 8; ++i )
  {
      for ( j = 1; j < 8-i; ++j )
       {
        printf("%d ", arr[j]);
        printf("\n");

        if ( arr[j] > arr[j+1] )
	         swap( &arr[j], &arr[j+1] );
        }
  }

You can add another for loop after the sorting operation is complete, to print the sorted array, instead of printing array elements inside sorting loops (unless being used for debugging purpose.)

Good luck.
  #8  
Old 07-Nov-2004, 23:20
doc_watson2007 doc_watson2007 is offline
New Member
 
Join Date: Oct 2004
Posts: 7
doc_watson2007 is on a distinguished road

array swapping


Quote:
Originally Posted by nkhambal
Another problem with your program is the for loops you are using for sorting the array. You are not using { } brackets after each "for" statment. If you do not use {} brackets after any of your loop conditions, only the statment next to your loop condition will be executed.

Following lines of code
CPP / C++ / C Code:
for ( i = 0; i < 8-1; ++i )
      for ( j = 1; j < 8-i; ++j )
      printf("%d ", arr[j]);
      printf("\n");

        if ( arr[i-1] > arr[j] )
            swap( arr[i-1], arr[j] );

Will effectively only execute first printf in the inner for loop. You need to use {} properly in your loops to get the required results.

Also, there is a problem with the sort logic in your for loops. It should be.

CPP / C++ / C Code:
for ( i = 0; i < 8; ++i )
  {
      for ( j = 1; j < 8-i; ++j )
       {
        printf("%d ", arr[j]);
        printf("\n");

        if ( arr[j] > arr[j+1] )
	         swap( &arr[j], &arr[j+1] );
        }

  }

You can add another for loop after the sorting operation is complete, to print the sorted array, instead of printing array elements inside sorting loops (unless being used for debugging purpose.)

Good luck.
I have started from the beginning, this is what I have accomplish so far. I am still having probs with it printing the 2 thru 8 arrays. Hopefully I post this correctly.
CPP / C++ / C Code:
#include <stdio.h>

#define N 8

void order(int *p, int *q);

int main(void)
{
int    a[] = {7, 3, 66, 3, -5, 22, -77, 2}; 
int    i; 
int    j; 
int    k; 

   /* main program */

printf("\n   Unordered data:");
for (k = 0; k < N; ++k)  
	printf("%6d", a[k]);  
	    printf("\n");        

		for (i = 0; i < N; ++i) 
						
			for (j = i + 1; j < N; ++j)
								
	/*Compare Data*/
				
if (a[i] > a[j])
	order(&a[i], &a[j]);
		printf("     After pass %d:", ++i);
	for (k = 0; k < N; ++k)
		printf("%6d", a[k]);
			printf("\n");
return 0;
}
void order(int *p, int *q)

/* Swap Function* /
{
   int tmp;

   tmp = *p;
   *p = *q;
   *q = tmp;
}
  #9  
Old 08-Nov-2004, 00:14
nkhambal nkhambal is offline
Regular Member
 
Join Date: Jul 2004
Location: CA USA
Posts: 313
nkhambal is a jewel in the roughnkhambal is a jewel in the rough
I don't see any problem with your code, except one typo which is causing you entire function definition of order to be commented out.

Following line had problem

CPP / C++ / C Code:
/* Swap Function* /

It should be

CPP / C++ / C Code:
/* Swap Function */


Following code complied correctly and executed and given proper result to me.

CPP / C++ / C Code:
#include <stdio.h>

#define N 8

void order(int *p, int *q);

int main(void)
{
int    a[] = {7, 3, 66, 3, -5, 22, -77, 2};
int    i;
int    j;
int    k;

   /* main program */

printf("\n   Unordered data:");
for (k = 0; k < N; ++k)
  printf("%6d", a[k]);
      printf("\n");

    for (i = 0; i < N; ++i)

      for (j = i + 1; j < N; ++j)

  /*Compare Data*/

if (a[i] > a[j])
  order(&a[i], &a[j]);
    printf("     After pass %d:", ++i);
  for (k = 0; k < N; ++k)
    printf("%6d", a[k]);
      printf("\n");
return 0;
}
void order(int *p, int *q)

/* Swap Function */

{
   int tmp;

   tmp = *p;
   *p = *q;
   *q = tmp;
}

Following was the output when I executed it.

Quote:

Unordered data: 7 3 66 3 -5 22 -77 2
After pass 9: -77 -5 2 3 3 7 22 66

The reason its printing only pass 9 is because you have not used {} after if statement. That why if is only executing order function calls specified number times by two for loops. When it is out of for loops, its executing your printf statment. If you want print to be executed in each pass you need to use {} properly. I would like you to try it out yourselve.
  #10  
Old 08-Nov-2004, 00:21
WaltP's Avatar
WaltP WaltP is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Midwest US
Posts: 3,258
WaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to all
Quote:
Originally Posted by doc_watson2007
I have started from the beginning, this is what I have accomplish so far. I am still having probs with it printing the 2 thru 8 arrays. Hopefully I post this correctly.

Your bracketting and formatting makes your program very difficult to follow. Check the format tutorial...
CPP / C++ / C Code:
#include <stdio.h>
#define N 8
void order(int *p, int *q);

int main(void)
{
    int    a[] = {7, 3, 66, 3, -5, 22, -77, 2}; 
    int    i; 
    int    j; 
    int    k; 

       /* main program */

    printf("\n   Unordered data:");
    for (k = 0; k < N; ++k)  
    {
        printf("%6d", a[k]);  
    }
    printf("\n");        

    for (i = 0; i < N; ++i) 
    {
        for (j = i + 1; j < N; ++j)
        {
            /*Compare Data*/
            if (a[i] > a[j])
            {
                order(&a[i], &a[j]);
            }
        }
    }
    printf("     After pass %d:", ++i);
    for (k = 0; k < N; ++k)
    {
        printf("%6d", a[k]);
    }
    printf("\n");
    return 0;
}

/* Swap Function* /
void order(int *p, int *q)
{
   int tmp;

   tmp = *p;
   *p = *q;
   *q = tmp;
}
Now add some comments so you can keep track of what sections do what. You may be able to find your problem easily now.
__________________

Got a cough? Go home tonight and eat a whole box of Ex-Lax. Tomorrow, you'll be afraid to cough.
-- Pearl Williams
 
 

Recent GIDBlogWriting a book by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Deleting elements of arrays C++ the_crazyman C++ Forum 25 30-May-2008 08:27
Knight tour (arrays help needed) dilmv C++ Forum 7 18-Oct-2004 15:31
problem with arrays melas C Programming Language 5 12-Oct-2004 05:18
sorting question fj8283888 C Programming Language 1 13-Apr-2004 21:42
need help with passing 3 arrays into a function tommy69 C Programming Language 14 07-Apr-2004 01:22

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 03:47.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.