Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

sort function for array elements

Status
Not open for further replies.

tinycities

Programmer
Oct 31, 2000
6
0
0
US
Hi I'm trying to sort an array's elements into sequential order. When I run my program I am able to read the input from my input file, and then store that input in my array, but I can't get it to sort properly. I've pasted my sort function below. if you have any ideas please let me know. Thanks!

void sort (int arr[], int size, int& num_used)
{
bool sorted = false;
while (sorted == false)
{
sorted = true;
for (int index = 0; index < size - 1 && index < num_used - 1; index++)
{
if (arr[index] > arr[index+1])
{
int tmp = arr[index];
arr[index] = arr[index+1];
arr[index+1] = tmp;
sorted = false;
}//end if
}//end for
}//end while
}//end sort func.

 
I haven't looked at the entire program cautiously, but one thing instantly caught my eye.

Inside the 'for loop', why are you stating the while condition as &quot;index < arr.size() - 1&quot;. Shouldn't it be &quot;index <= arr.size() - 1&quot;. From your while condition, the procedure will not check the last element. Imagine 20 array elements. Your statment says, index < 19. You forget to compare the last two elements. Another valid statement is &quot;index < array.size()&quot;
And even after you corrected it, your &quot;sorted&quot; variable will still read false because of where you have put it. You might want to work on the program again because I am not quite sure if 'tis right.
I am working on a proj. of my own, so I don't have the time to look. Im sure someone else might help.

Narayanan Srinivasan
coolie91@hotmail.com

Brothers and Sisters from India, if you have any recent news regarding F-1 to H-1B visa transfer, please e-mail me. Thanks.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top