papi
papi

Reputation: 389

Sorting numbers with c++

So, I wrote the program that sorts numbers, but whenever I execute it, it adds smallest random number as a first one in "Sorted Numbers" line.

Here's a code:

#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include <time.h>

using namespace std;

int main(){

    const int MAX_SIZE = 100;
    int numbers[MAX_SIZE];
    int numElements;

    cout << "=============================" << endl;
    cout << "Welcome to BubbleSort Program" << endl;
    cout << "=============================" << endl;
    cout << endl;

    cout << "How many random numbers do you want us to produce? ";
    cin >> numElements;
    cout << endl;


    srand(static_cast<unsigned int>(time(0)));

    cout << "=============================" << endl;
    cout << "Random numbers: " << endl;
    cout << "=============================" << endl;

    for(int i = 0; i < numElements; i++){

        numbers[i] = (rand()%100) + 1;
        cout << numbers[i] << endl;
        if(i == numElements){
            cout << "i";
        }
    }


    int exchanges;
    int temp;
    int j;

    cout << "=============================" << endl; 
    cout << "Sorted numbers: " << endl;
    cout << "=============================" << endl;

    for(int i = 0; i <= numElements; i++){
        for(int j = 0; j < numElements; j++){

            if(numbers[j] > numbers[j + 1]){

                temp = numbers[j];
                numbers[j] = numbers[j + 1];
                numbers[j + 1] = temp;

            }
        }
    }

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

    cout << "=============================" << endl;
    return 0;
}

Output example:

============================= Welcome to BubbleSort Program =============================

How many random numbers do you want us to produce? 3

=============================
Random numbers:
=============================
69
8
5
=============================
Sorted numbers:
=============================
-858993460
5
8
69
=============================
Press any key to continue . . .

Soo.. WTF is -858993460?!

Upvotes: 1

Views: 5645

Answers (2)

aplassard
aplassard

Reputation: 759

Your issue is in your sorting implementation. You have an array of size 100 and you add 3 elements. By going to <= numElements, you are accessing array locations 0, 1, 2, and 3 and thus you are accessing an extra element. Change it to < and you'll be ok.

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201537

You're accessing uninitialized memory -

for(int i = 0; i <= numElements; i++) { // <-- no, stop at < -- see above.
  for(int j = 0; j < numElements; j++) // <-- you use j+1 below

Should be

for (int i = 0; i < numElements; i++) { // <-- also not initialized.
  for (int j = 0; j < numElements - 1; j++) // <-- like so.

Upvotes: 3

Related Questions