Example 1: bubble sort javascript
bubbleSort(Array) {
let len = Array.length;
for (let i = 0; i < len; i++) { //you can also use "for in", so you don't need the variable "len"
for (let j = 0; j < len; j++) {
if (Array[j] > Array[j + 1]) {
let tmp = Array[j];
Array[j] = Array[j + 1];
Array[j + 1] = tmp;
}
}
}
return Array;
};
Example 2: javascript bubble sort
const bubbleSort = (arr) => {
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length - i; j++) {
if (arr[j] > arr[j + 1]) {
let tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
return arr;
}
Example 3: bubble sort in java
public static void bubbleSort(int arr[])
{
for (int i = 0; i < arr.length; i++) //number of passes
{
//keeps track of positions per pass
for (int j = 0; j < (arr.length - 1 - i); j++) //Think you can add a -i to remove uneeded comparisons
{
//if left value is great than right value
if (arr[j] > arr[j + 1])
{
//swap values
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
Example 4: bubble sort c
using namespace std;
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// A function to implement bubble sort
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver code
int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
cout<<"Sorted array: \n";
printArray(arr, n);
return 0;
}
Example 5: bubble sort javascript
function bubblesort(array) {
len = array.length;
for (let i = 0; i < len; i++) {
for (let j = 0; j < len - i; j++) {
let a = array[j];
if (a != array[-1]) {
var b = array[j + 1];
if (a > b) {
array[j] = b;
array[j + 1] = a;
}
}
}
}
}
let array = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
bubblesort(array);
console.log(array)
Example 6: bubble sort javascript
function bubbleSort(array) {
const len = array.length;
const retArray = array;
for (let i = 0; i < len; i++) {
for (let j = 0; j < len - i; j++) {
const a = array[j];
if (a !== array[-1]) {
const b = array[j + 1];
if (a > b) {
retArray[j] = b;
retArray[j + 1] = a;
}
}
}
}
return retArray;
}
bubbleSort([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);