sorting algorithm not working correctly
I can't seem to get this sorting alogorithm to work:
Code:
#include <iostream>
void sortAssending(int nums[], int size);
int main()
{
int nums[] = {175,167,160,164,183,187,188,179,176,175,
169,175,176,178,165,160,173,165,187,178};
sortAssending(nums, 20);
for (int i=0; i<20; i++)
{
std::cout << nums[i] << std::endl;
}
system("PAUSE");
}
void sortAssending(int nums[], int size)
{
for (int start=0; start<size; start++)
{
for (int end=size-1; end>=0; end--)
{
if (nums[start] > nums[end])
{
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
}
}
}
}
It seems to do everything right except the very end. Can anyone spot the problem?
Re: sorting algorithm not working correctly
PHP Code:
template <class T>
void bubble(T *x, int n)
{
int i, j;
for (i = 0; i < n-1; ++i)
for (j = i+1; j > 0; --j)
if (x[j] < x[j-1]) swap(x[j], x[j-1]);
}
See if that works for you. I must warn you. Bubble sorting is so slow that it's practically useless.
Re: sorting algorithm not working correctly
Minor point: it's "ascending".
Re: sorting algorithm not working correctly
Quote:
Originally Posted by System_Error
Code:
void sortAssending(int nums[], int size){
for (int start=0; start<size; start++){
for (int end=size-1; end>=0; end--){
if (nums[start] > nums[end]){
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
}
}
}
}
Try changing the 'end >= 0' to 'end > start'
Then, it becomes just a weird form of selection sort in disguise:
For each start (0 -> size - 1), assuming the first #start objects are sorted:
Put the next smallest into nums[start]. This sorts the first #start + 1 objects, and completes the inductive proof.