Sorting Arrays

i know about bubble sorting but what im trying to do is swap the values that i want but it doesnt work i dont know why can anybody help?



#include "stdafx.h"
#include "iostream"
#include "iomanip"



using namespace std;
using std::setw;


int _tmain(int argc, _TCHAR* argv[])
{
const int arraySize = 10;
int n[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
int hold = 0;


cout << "Data items in original order:" << endl;
for ( int i = 0; i < arraySize; i++ )
cout << setw( 4 ) << n [ i ];

cout << endl << endl;

swap ( n [ 2 ], n [ 3 ] );
cout << n[ arraySize ];




return 0;
}


im trying to change the 6 to 4 and the 4 to 6.
6 is stored at n[1] and 4 is stored at n[2] so it should be swap(n[1], n[2]);
Ok so when I print out the array after swapping I get a large negative number and not the sorted array how come?
You are not sorting the array. You are just swapping two elements in the array.

cout << n[ arraySize ]; This is probably the reason why it prints a large negative number. n[arraySize] is the element after the last element in the array.
Try #including <algorithm> and using the code std::sort(n[0], n[arraySize-1]);

See below post:
Last edited on
This will work better than what L B wrote std::sort(n, n + arraySize);
Last edited on
yeah its not working here this is what it is supposed to do ~~~~~~~~~~~~~~~~>


Data items in original order
2 6 4 8 10 12 89 68 45 37

After pass 0: 2 4 6 8 10 12 68 45 37 89
After pass 1: 2 4 6 8 10 12 45 37 68
After pass 2: 2 4 6 8 10 12 37 45
After pass 3: 2 4 6 8 10 12 37
After pass 4: 2 4 6 8 10 12
After pass 5: 2 4 6 8 10
After pass 6: 2 4 6 8
After pass 7: 2 4 6
After pass 8: 2 4

Data items in ascending order
2 4 6 8 10 12 37 45 68 89
Number of comparisons = 45.




i have no idea what im doing wrong!
Topic archived. No new replies allowed.