C Bubble Sort: отсортированный массив теряет большую часть данных и заменяется адресом памяти

Вывод получаю:

  • Базовый массив
  • 7290 5184 6174 8003 7427 2245 6522 6669 8939 4814
  • Сортированный массив
  • -33686019 2245 4814 5184 6174 6522 6669 7290 7427 8003
  • Нажмите любую клавишу для продолжения . , ,

Я понятия не имею, откуда этот номер -33686019. Я разместил весь код, потому что я действительно не знаю, что может быть причиной этого.

Пузырь Сортировать:

#include "Sorting.h"
double Sorting::bubbleSort( int size )
{
//Make a copy of our "master key" array for us to sort
int *toSort = whichArray(size);
int *theArray = copyArray( toSort, size );
double time;

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

//The sort

//Begin time
timer.startClock();

bool swapped = true;
int temp = 0;

while( swapped == true )
{
swapped = false;

for( int i = 0; i < size; i++ )
{
if( theArray[i+1] < theArray[i] )
{
/*temp = theArray[i+1];

theArray[i+1] = theArray[i];
theArray[i] = temp;*/

swap(theArray[i + 1], theArray[i]);
swapped = true;
}
}
}

time = timer.getTime();

cout << "The Sorted array" << endl;
for(int x = 0; x < 10; x++ )
{
cout << theArray[x] << endl;
}

return time;
}

Класс сортировки:

#ifndef SORTING_H
#define SORTING_H

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//^For random numbers
#include <iostream>

#include "TimerSystem.h"#include <iomanip>

using namespace std;

class Sorting
{
private:
//The below pointers will point to arrays that hold the data sets
int *n10;
int *n100;
int *n1000;
int *n10000;

TimerSystem timer;

double runs[4][4];

public:
Sorting();
~Sorting(){};

//Testing functions
void printArray();
void print2DArray();
void dryRun();

//Data manging and creating
int randomNumGen();
int* arrayGen( int size );//Returning a pointer
int* copyArray( int *toCopy, int size );//Makes an array that the program can sort. The leaves the original array intact
int* whichArray( int size );
void datasetRun( int whichSort );//Does three runs of a sort and gets the average for all 4 array sizes

//Sorts
double bubbleSort( int size );
};

#endif

Другие вызываемые функции:

#include "Sorting.h"
int Sorting::randomNumGen()
{
int randomNumber = rand() % 10000 + 1;

if( randomNumber > 10000 || randomNumber < 0 )
{
system("pause");
}

return randomNumber;
}

int* Sorting::arrayGen( int size )
{
int *theArray= new int[size];

for( int i = 0; i < size; i++ )
{
theArray[i] = randomNumGen();
}

return theArray;
}

int* Sorting::copyArray( int *toCopy, int size )
{
int *newArray = new int[size];

for( int i = 0; i < size; i++ )
{
newArray[i] = toCopy[i];
}

return newArray;
}

int* Sorting::whichArray( int size )
{
if( size == 10 )
{
return n10;
}
else if( size == 100 )
{
return n100;
}
else if( size == 1000 )
{
return n100;
}
else if( size == 10000 )
{
return n1000;
}

return NULL;
}

void Sorting::datasetRun( int whichSort )
{
//1: Bubble
//2: Insertion
//3: Selection
//4: Shell
//5: Quick
//6: Merge

int col = 0;
int row = 0;
int set = 10;
bool runDone = false;

if( whichSort == 1 )
{
for( int row = 0; row < 4; row++ )
{
for( int col = 0; col < 4; col++ )
{
runs[row][col] = bubbleSort( set );
}

//set = set * 10;
}
}
}

//Constructor
Sorting::Sorting()
{
//For the random number generator
srand( time(NULL) );

n10 = arrayGen( 10 );
n100 = arrayGen( 100 );
n1000 = arrayGen( 1000 );
n10000 = arrayGen( 10000 );
}

//Functions for testing
void Sorting::printArray()
{
int size = 10000;

for( int i = 0; i < size; i++ )
{
cout << n10000[i] << " ";
}
}

void Sorting::print2DArray()
{
for( int height = 0; height < 4; height++ )
{
for( int width = 0; width < 4; width++ )
{
cout << runs[height][width] << endl;
}

cout << "\n\n";
}
}

Основная функция:

#include "Sorting.h"
void main()
{
//Makes the numbers easily readable
cout.setf(ios::fixed | ios::showpoint);
cout.precision(16);

Sorting theSorting;

//theSorting.printArray();

//cout << theSorting.bubbleSort( 10 ) << endl;

//theSorting.datasetRun(1);
//theSorting.print2DArray();

theSorting.bubbleSort( 10 );

system("pause");
}

1

Решение

Следующий бит не верен:

for( int i = 0; i < size; i++ )
{
if( theArray[i+1] < theArray[i] )

Это доступ к одному за границей массива. for цикл, вероятно, должен быть:

for( int i = 0; i < size - 1; i++ )
6

Другие решения

Посмотри на это:

for( int i = 0; i < size; i++ )
{
if( theArray[i+1] < theArray[i] )

theArray [i + 1] не определено на последней итерации цикла.

Измените выражение продолжения цикла с i < size в i < (size-1)

3