Click to See Complete Forum and Search --> : Sorting a simple 1d array?


sublim21
04-22-2003, 05:43 PM
Hey guys, im still working on my program. However, im running into a problem. I have a simple 1d array that starts at array[1] to array[7] and im trying to sort the array, by increasing values.
This is the code i have written, however its not working.
std::sort(& array[1],& array[8]);
when i cout the values of array[1] through array[7] they're clearly have not been sorted. :(
If you guys could help explain as to why this happens, im all ears. :)
Thanks,
Peter.

Handyman
04-22-2003, 07:45 PM
What does your sorting function look like?? Or is it a built-in function of one of the libraries?

Also, you say you are sorting from index 1 to 7, what about the 0 index? And in your function call you send an index of 8 as one of your parameters. Something might be wrong there... maybe.

Handyman
04-22-2003, 07:48 PM
Website I found from a quick search... might be helpful :)

http://www.devarticles.com/art/1/76/2

EverlastingGod
04-23-2003, 10:35 AM
Is it changing the values at all? If so, what sort is using to compare two elements is wrong. You might have to overload <.

What are you sorting? The syntax is correct...

#include <algorithm>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
int array[] = {1, 3, 5, 2, 4, 1, 3, 7, 10, 9};
std::sort(&array[1], &array[8]);

for (int i = 0; i < 10; i++)
{
cout << array[i] << endl;
}
}


Output:
1
1
2
3
3
4
5
7
10
9

sublim21
04-24-2003, 12:11 AM
Hey guys, thanks. I kept messing around, and sorting through some stuff, and found some code thats called bubblesorting. I mimicked the simple code, and it did what i needed it to do. I appreciate the help guys. :)
On a side note - Todays final exam railed me in the butt. :(
The Code i used is at the bottom.
Oh, if you ever need to find out if 8 points make a cube, feel free to use my code. :)
It can be found here :) (http://www.noidea128.org/cgi-bin/framesource.cgi?id=1727&type=html)
void swap(float& x, float& y)
{
float temp = x; // Use temp to store x temporarily
x = y;
y = temp;
}

//************************************************************ *************

// The bubble sort

void bubbleSort(float a[], int n) // n is size of array to sort
{
for (int i = 1; i < n; i++) // Make n-1 passes
{
for (int j = 0; j < n-i; j++) // Lowest index of pair = n-i-1
{
if(a[j] > a[j+1]) // a[j] should be less than a[j+1]
{
swap(a[j], a[j+1]);
}
cout << "Array after pass " << i << ", pair " << j << " and " <<
j+1 << endl;
printArray(a, 5);
}
}
}

EverlastingGod
04-24-2003, 08:57 AM
std::sort should have worked with floats...