हमें एक JavaScript फंक्शन लिखना है जो लिटरल्स का ऐरे लेता है और बबल सॉर्ट का उपयोग करके इसे सॉर्ट करता है। बबल सॉर्ट में, आसन्न एलिमेंट्स के प्रत्येक जोड़े की तुलना की जाती है और यदि वे क्रम में नहीं हैं तो एलिमेंट्स को स्वैप किया जाता है।
उदाहरण
आइए इस फंक्शन के लिए कोड लिखें -
const arr = [4, 56, 4, 23, 8, 4, 23, 2, 7, 8, 8, 45];
const swap = (items, firstIndex, secondIndex) => {
var temp = items[firstIndex];
items[firstIndex] = items[secondIndex];
items[secondIndex] = temp;
};
const bubbleSort = items => {
var len = items.length,
i, j;
for (i=len-1; i >= 0; i--){
for (j=len-i; j >= 0; j--){
if (items[j] < items[j-1]){
swap(items, j, j-1);
}
}
}
return items;
};
console.log(bubbleSort(arr));
आउटपुट
कंसोल में आउटपुट: -
[
2, 4, 4, 4, 7,
8, 8, 8, 23, 23,
45, 56
]