/ / Výber triedenia bublín nie je zoradený - c ++, triedenie, výstup, triedenie bublín

Produkt triedenia bublín nie je zoradený - c + +, triedenie, výstup, triedenie bublinami

Môj kód funguje, keď je vložený do funkcie int main (), ale keď ho implementujem ako ďalšiu funkciu (void bubbleSort), výstup zobrazí, ako keby nebolo vykonané žiadne triedenie.

void bubbleSort(int numeros[])
{
int store = 0;
int length = ARRAY_SIZE(numeros);
for(int i=0; i<(length-1); i++)
{
for(int j=0; j<(length-i-1); j++)
{
if(numeros[j] < numeros[j+1])
{
store = numeros[j];
numeros[j] = numeros[j+1];
numeros[j+1] = store;

}
}
}
for(int m=0; m<1000; m++)
{
cout << numeros[m] <<" ";
}
}

Čo som mohol urobiť zle? Akákoľvek pomoc by bola veľmi ocenená.

odpovede:

1 pre odpoveď č. 1

Nemôžete preniesť celé pole ako argument pre ac ++, iba ukazovateľ na prvý prvok v poli. V dôsledku toho potrebujete nejaký spôsob, ako uviesť funkciu, ako dlho je pole. Jedným zo spôsobov, ako to prejsť ako ďalší argument (ako je uvedené nižšie). Existuje nejaká diskusia a návrhy ďalších / lepších spôsobov, ako to urobiť tu.

Napríklad, ak omylom prejdete zle length argumenty pre tieto funkcie začnú pracovať na akejkoľvek pamäti, ktorá existuje po bloku pamäte, kde je vaše pole.

#include <iostream>

using namespace std;

void printArray(int array[], int length) {
for(int i=0; i<length; i++) {
cout << array[i] << " ";
}
cout << endl;
}

void bubbleSort(int numeros[], int length) {
int store = 0;
for(int i=0; i<(length-1); i++) {
for(int j=0; j<(length-i-1); j++) {
if(numeros[j] < numeros[j+1]) {
store = numeros[j];
numeros[j] = numeros[j+1];
numeros[j+1] = store;
}
}
}
cout << "array at end of bubble sort: ";
printArray(numeros, length);
}

int main() {
int anArray[] = {1, 3, 2, 4, 6, 5, 10, 9, 7, 8};
int arraySize = sizeof(anArray)/sizeof(anArray[0]);
cout << "arraySize: " << arraySize << endl;
cout << "array before sort: ";
printArray(anArray, arraySize);
bubbleSort(anArray, arraySize);
cout << "array after sort: ";
printArray(anArray, arraySize);
return 0;
}