Javascripttel megoldva
KIHÍVÁS ( bubbleSort )
A bubbleSort egy tömb első eleménél kezdődik, és összehasonlítja a második elemmel, ha az első elem nagyobb, mint a második elem, felcseréli a kettőt. Ezután összehasonlítja a másodikat a harmadikkal, a harmadikat a negyedikkel, és így tovább. Amikor eléri a végét, elölről kezdődik, és addig ismétli, amíg minden számszerűen nincs rendezve.
Valósítson meg egy függvényt, amely ezt a .sort() metódusba épített javascriptek használata nélkül teszi meg
Példák
A bubbleSort([2,5,3]) a [2, 3, 5] értéket adja vissza
A bubbleSort([4,3,7,2,1]) az [1, 2, 3, 4, 7] értéket adja vissza
Edge tokok
Egyik sem kell aggódnia az elszámolás miatt
A kód
Először is vázoljuk fel ennek a problémának a vázát. Ez egy meglehetősen gyakori minta, amelyet látni fog, ha rekurziót használ a kódban.
let bubbleSort = function(array){ // we'll need a variable to keep track of whether or not we had to sort anything on any particular iteration let swapCount = 0; // then we'll create a helper function let helper = function(array){ // heres where the magic happens, we'll break this down in a sec } // we'll have to call our helper function helper(array); // when the helper function stops running then we return the result ( our sorted array ) return array; }
Tehát mi történik a segítő funkcióban?
let helper = function(array) { // each time we call the helper function we need to make sure that we reset our swapCount to 0; swapCount = 0; // loop through the array for (let i = 0; i < array.length - 1; i++) { // if the value of the current index is greater than the value of the following index then ... if(array[i] > array[i + 1]) { // increase the swapCount value by 1 ... swapCount ++; // create variables that point to the current value and the next value let current = array[i]; let next = array[i + 1]; // swap the values by manually setting the value of the array indices array[i] = next; array[i + 1] = current; } } // if we looped through the array and did not have to swap anything then break out of the function with a return statement if (swapCount === 0) { return; } // if swapCount has a value greater than 0 then that means we keep sorting, call the helper function again! helper(array); }
Íme a kód teljes verziója:
let bubbleSort = function(array) { let swapCount = 0; let helper = function(array) { swapCount = 0; for (let i = 0; i < array.length - 1; i++) { if(array[i] > array[i + 1]) { swapCount ++; let current = array[i]; let next = array[i + 1]; array[i] = next; array[i + 1] = current; } } if (swapCount === 0) { return; } helper(array); } helper(array); return array; };
Erről az általánosan használt rendezési algoritmusról bővebben ITT olvashat
Ez csak egy a sok lehetséges megoldás közül, remélem, segített jobban megérteni a probléma megközelítését. Köszönöm, hogy elolvastad, és ha hasznosnak találtad, kérlek, tapsolj!
Keress meg a GitHubon