![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Hobbyist Programmer
Join Date: Mar 2006
Posts: 115
Rep Power: 3
![]() |
sort and swap
Hi,
I want to write a function in which I have an array list that contains random permutation of integers from 0 to 51. Then, we use a ascending selection sort selsort to sort list- but with each swap in the sort, also swap the corresponding cards (rows) in the deck. deck is of type arrays of strings. its declaration is like char deck[5][20]={"two of clubs","three of clubs","four of clubs", "five of clubs","six of clubs","seven of clubs", "eight of clubs","nine of clubs","ten of clubs", "jack of clubs","queen of clubs","king of clubs", "ace of clubs","two of spades",......... the code for the ascending sort is: (NOTE: I modified this code by adding the red instructions to solve the problem) void selsort(int x[ ],int n)
/* purpose: to sort a numerical vector in ascending order using
the selection sort algorithm
parameters: x -- the array to be sorted/input&output
n -- the number of elements in the array */
{ int min; /*position of minimum*/
int i,j; /*counters for loops */
float t; /*temporary hold for interchange*/
char deck[5][20];
/*outer loop to find min of what is left */
for(i=0;i<n-1;i++)
{ min = i; /*assume smallest in current position*/
for(j=i+1;j<n;j++) /*look thru rest*/
{
if(x[j]<x[min]) /*see if less than current min */
min = j; /*yes, so note its position */
}
t = x[i]; /*found min so move it into position */
x[i]=x[min];
x[min] = t;
swap(deck,i,j);
} /*end of outer loop*/
} /*end of function */My swap function is: void swap(char terms[][20],int i,int j)
{
char temp[20];
strcpy(temp,terms[i]);
strcpy(terms[i], terms[j]);
strcpy( terms[j],temp);
}When I execute selsort, I get a wrong sorting, and when I try to print deck, it just give me one card.(when I removed the red instructions,the function selsort is OK) I really dont know why that happened. Please,can someone tell me (suggestions) why I have those two problems? How to get at the same time a good sorting( from 0 to 51) and be able to print the shuffled deck? Or my approach is wrong..... B. |
|
|
|
|
|
#2 |
|
Expert Programmer
Join Date: Jun 2005
Posts: 824
Rep Power: 4
![]() |
swap(deck,i,j); swap(deck,i,min); |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|