Search
 
SCRIPT & CODE EXAMPLE
 

C

bubbleSort

const bubbleSort = (arr) => {
  let temp = 0;
  for (let i = 0; i < arr.length; i++) {
    for (let j = 1; j < arr.length; j++) {
      if (arr[j - 1] > arr[i]) {
        temp = arr[j - 1];
        arr[j - 1] = arr[i];
        arr[i] = temp;
      }
    }
  }
  return arr;
};

console.log(bubbleSort([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]));
Comment

bubble sort

arr = [12,1,6,23,234,456,2,35,687,34]
# arry consists of 9 elements

n = len(arr)
#conts the element of the arry 

for j in range(n-1):            #this is for list to get shorted properly && you dont need to go full as it may take more steps to exicute
    for i in range(n-j-1):      #if left with n the there will be array error because it will try to add 1 to n in below leading to array being bigger                                             
        if arr[i]>arr[i+1]:                                         
            arr[i],arr[i+1]=arr[i+1],arr[i]
        else:
            pass
#       arry starts from last and eventually decrease the number lower and lower which leads to lesser steps
#       #above took 125 steps to eully exicute
#################################################################        
#       #this takes 217 steps to run and end code
# for i in range(n):
#     if arr[i]>arr[i+1]:
#         arr[i],arr[i+1]=arr[i+1],arr[i]        
#     else:
#         pass
#################################################################    
print("the sorted array is : "arr)
Comment

Bubble Sort

#Bubble Sort
nums = [9, 4, 5, 1, 3, 7, 6]
for i in range(len(nums)):
    for j in range(1, len(nums)):
        if nums[j] < nums[j - 1]:
            nums[j], nums[j - 1] = nums[j - 1], nums[j]
Comment

Bubble sort

public class BubbleSortExample {  
    static void bubbleSort(int[] arr) {  
        int n = arr.length;  
        int temp = 0;  
         for(int i=0; i < n; i++){  
                 for(int j=1; j < (n-i); j++){  
                          if(arr[j-1] > arr[j]){  
                                 //swap elements  
                                 temp = arr[j-1];  
                                 arr[j-1] = arr[j];  
                                 arr[j] = temp;  
                         }  
                          
                 }  
         }  
  
    }  
    public static void main(String[] args) {  
                int arr[] ={3,60,35,2,45,320,5};  
                 
                System.out.println("Array Before Bubble Sort");  
                for(int i=0; i < arr.length; i++){  
                        System.out.print(arr[i] + " ");  
                }  
                System.out.println();  
                  
                bubbleSort(arr);//sorting array elements using bubble sort  
                 
                System.out.println("Array After Bubble Sort");  
                for(int i=0; i < arr.length; i++){  
                        System.out.print(arr[i] + " ");  
                }  
   
        }  
}  
Comment

bubble sort

def bubble_sort(nums):
    n = len(nums)
    for i in range(n):
        swapped = False
        for j in range(1, n - i):
            if nums[j] < nums[j - 1]:
                nums[j], nums[j - 1] = nums[j - 1], nums[j]
                swapped = True
        if not swapped: break
    return nums
print(bubble_sort([9, 8, 7, 6, 5, 4, 3, 2, 1]))
Comment

bubble sort

// C program for implementation of Bubble sort
#include <stdio.h>
  
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++)
        printf("%d ", arr[i]);
    printf("
");
}
  
// Driver program to test above functions
int main()
{
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr)/sizeof(arr[0]);
    bubbleSort(arr, n);
    printf("Sorted array: 
");
    printArray(arr, n);
    return 0;
}
Comment

bubblesort

"""Bubblesort
"""
## Un-optimised--------------------------------------------------------------
def bubble_1(lst):
    n = len(lst) - 1
    for i in range(n):
        # Within the unsorted portion
        for j in range(n - i):
            # If curr > next, swap
            if lst[j] > lst[j+1]:
                lst[j], lst[j+1] = lst[j+1], lst[j]
    return lst # for easy testing

def bubble_2(lst):
    n = len(lst) - 1
    # Within the unsorted portion, except the last number
    for unsorted in range(n, 0, -1):
        for i in range(unsorted):
            # If curr > next, swap
            if lst[i] > lst[i+1]:
                lst[i], lst[i+1] = lst[i+1], lst[i]
    return lst # for easy testing

## Optimised-----------------------------------------------------------------
def bubble_3(lst):
    n = len(lst) - 1
    
    # Within the unsorted portion, except the last number
    for unsorted in range(n, 0, -1):
        swapped = False
        for i in range(unsorted):
            # If curr > next, swap
            if lst[i] > lst[i+1]:
                lst[i], lst[i+1] = lst[i+1], lst[i]
                swapped = True
        
        # Check if its sorted by this time
        if not swapped:
            break
    return lst # for easy testing
Comment

Bubble sort

public class BubbleSortExample {  
    static void bubbleSort(int[] arr) {  
        int n = arr.length;  
        int temp = 0;  
         for(int i=0; i < n; i++){  
                 for(int j=1; j < (n-i); j++){  
                          if(arr[j-1] > arr[j]){  
                                 //swap elements  
                                 temp = arr[j-1];  
                                 arr[j-1] = arr[j];  
                                 arr[j] = temp;  
                         }  
                          
                 }  
         }  
  
    }  
    public static void main(String[] args) {  
                int arr[] ={3,60,35,2,45,320,5};  
                 
                System.out.println("Array Before Bubble Sort");  
                for(int i=0; i < arr.length; i++){  
                        System.out.print(arr[i] + " ");  
                }  
                System.out.println();  
                  
                bubbleSort(arr);//sorting array elements using bubble sort  
                 
                System.out.println("Array After Bubble Sort");  
                for(int i=0; i < arr.length; i++){  
                        System.out.print(arr[i] + " ");  
                }  
   
        }  
}  
Comment

Bubble Sorting

import java.util.Arrays;
public class Bubble{
	public static void main(String[] args){
		int[] arr = {5,4,3,2,1}; // Test case array
		
		for(int i =0;i<arr.length-1;i++){ // Outer Loop
		boolean swap = false;
		  for(int j =1;j<arr.length;j++){ // Inner Loop
			  if(arr[j-1]>arr[j]){ // Swapping
				  int temp = arr[j-1];
				  arr[j-1] = arr[j];
				  arr[j] = temp;
				  swap = true;
			  }
		  }
		  if(!swap){ // If you went through the whole arrray ones and 
             break; // the elements did not swap it means the array is sorted hence stop  
		  }
		}
		
		System.out.print(Arrays.toString(arr));
	}
}
Comment

bubble sort algorithm

Bubble sort, aka sinking sort is a basic algorithm
for arranging a string of numbers or other elements
in the correct order. This sorting algorithm is
comparison-based algorithm in which each pair of
adjacent elements is compared and the elements are
swapped if they are not in order. The algorithm then
repeats this process until it can run through the
entire string or other elements and find no two
elements that need to be swapped. This algorithm is
not suitable for large data sets as its average and
worst case complexity are of Ο(n2) where n is the number of items.

In general, Just like the movement of air bubbles
in the water that rise up to the surface, each element
of the array move to the end in each iteration.
Therefore, it is called a bubble sort.
Comment

bubble sort code

func Sort(arr []int) []int {
	for i := 0; i < len(arr)-1; i++ {
		for j := 0; j < len(arr)-i-1; j++ {
			if arr[j] > arr[j+1] {
				temp := arr[j]
				arr[j] = arr[j+1]
				arr[j+1] = temp
			}
		}
	}
	return arr
}
Comment

bubble sort

#include<iostream>
void swap(int &a, int &b)
{
  int temp=a;
  a=b;
  b=temp;
}
void bubblesort(int arr[], int n)
{
  for(int i=0;i<n-1;i++)// why upto n-1?
  {
    for(int j=0;j<n-1;j++)
    {
      if(arr[j]>arr[j+1])
      {
        swap(arr[j],arr[j+1]);
      }
    }
  }
}
int main()
{
  int arr[5]={7, 8, 1, -4, 0};
  bubblesort(arr, 5);
  for(int i=0;i<5;i++)
  {
    std::cout<<arr[i]<<std::endl;
  }
}
Comment

bubble sort

// Go impelementation of Bubble Sort
package main

import "fmt"

func bubbleSort(arr []int) {
	// Finding the length of the array
	n := len(arr)

	for i := 0; i < n; i++ {
		for j := 0; j < n-i-1; j++ {
			// if the fist lement is greater than the second one then swap
			if arr[j] > arr[j+1] {
				arr[j], arr[j+1] = arr[j+1], arr[j]
			}
		}
	}
}

func printArray(arr []int) {
	n := len(arr)

	for i := 0; i < n; i++ {
		fmt.Print(arr[i], " ")
	}
	fmt.Println()
}

func main() {
	arr := []int{24,35,8,16,64}

	bubbleSort(arr)

	printArray(arr)
}
Comment

Algorithm of bubble sort

begin BubbleSort(list)

   for all elements of list
      if list[i] > list[i+1]
         swap(list[i], list[i+1])
      end if
   end for
   
   return list
   
end BubbleSort
Comment

bubble sort

// Bubble Sort algorithm -> jump to line 21

...

#include <iostream>      // Necessary for input output functionality
#include <bits/stdc++.h> // To simplify swapping process

...

...

/**
* Sort array of integers with Bubble Sort Algorithm
*
* @param arr   Array, which we should sort using this function
* @param arrSZ The size of the array
* @param order In which order array should be sort
*
* @return Sorted array of integers
*/
void bubbleSortInt(double arr[], int arrSz, string order = "ascending")
{
    for (int i = 0; i < arrSz; ++i)
    {
        for (int j = 0; j < (arrSz - i - 1); ++j)
        {
            // Swapping process
            if ((order == "descending") ? arr[j] < arr[j + 1] : arr[j] > arr[j + 1])
            {
                swap(arr[j], arr[j + 1]);
            }
        }
    }
    return; // Optional because it's a void function
} // end bubbleSortInt

...

int main()
{

...

    return 0; // The program executed successfully.

} // end main
Comment

bubble sort algorithm

#include <bits/stdc++.h>

using namespace std;

void bubbleSort(int arr[], int n){
    int temp,i,j;
    for(i=0;i<n;i++){
        for(j=i+1;j<n;j++){
            if(arr[i] > arr[j]){
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
}

int main(){
    int arr[] = {1,7,33,9,444,2,6,33,69,77,22,9,3,11,5,2,77,3};
    int n = sizeof(arr) / sizeof(arr[0]);

    bubbleSort(arr, n);

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

    return 0;

}
Comment

Bubble Sort

#include<bits/stdc++.h>
#define swap(x,y) { x = x + y; y = x - y; x = x - y; }

using namespace std;

/**
    * Function to Sort the array using Modified Bubble Sort Algorithm
    * @param arr: Array to be Sorted
    * @param n: Size of array
    * @return : None
*/
void bubbleSort(int arr[], int n)
{
    int i, j;
    bool flag;
    // Outer pass
    for(i = 0; i < n; i++)
    {
        flag = false;                                   // Set flag as false
        for(j = 0; j < n-i-1; j++)
        {
            // Compare values
            if( arr[j] > arr[j+1])
            {
                swap(arr[j],arr[j+1]);
                flag = true;
            }
        }
        // If no to elements are swapped then
        // array is sorted. Hence Break the loop.
        if(!flag)
        {
            break;
        }
    }
}
int main(int argv, char* argc[])
{
    int arr[] = {1,5,6,8,3,4,7,2,9};
    int n = sizeof(arr)/sizeof(int);
    cout<<"Unsorted Array :";
    for(int i=0;i<n;i++)                            // Print the Original Array
        cout<<arr[i]<<" ";
    cout<<endl;
    bubbleSort(arr,n);                              // Call for Bubble Sort Function
    cout<<"Sorted Array :";
    for(int i=0;i<n;i++)                            // Print the Sorted Array
        cout<<arr[i]<<" ";
    return(0);
}
Comment

bubble sort

int *BubbleSort(int ar[], int size)
{
    bool sorted = false;
    while (sorted == false)
    {
        sorted = true;
        for (int i = 0; i < size; i++)
        {
            if (ar[i] > ar[i + 1])
            {
                swap(ar[i], ar[i + 1]);
                sorted = false;
            }
        }
    }
    return ar;
}
Comment

bubble sort

const bubbleSort = (arr) => {
  for (let i = 0; i < arr.length - 1; i++) {
    for (let j = 0; j < arr.length - 1; j++) {
      // compare arr[j] to arr[j+1]
      // swap places if needed
    }
  }

  return arr;
};
Comment

bubble sort

const bubbleSort = (arr) => {
  let sorted = false;

  while (!sorted) {
    sorted = true;

    for (let i = 0; i < arr.length - 1; i++) {
      // compare arr[i] to arr[i+1]
      // swap places if needed
      // if swapped, set sorted = false to run while loop again
    }
  }

  return arr;
};
Comment

Bubble sort

bubbleSort(array)
  swapped <- false
  for i <- 1 to indexOfLastUnsortedElement-1
    if leftElement > rightElement
      swap leftElement and rightElement
      swapped <- true
end bubbleSort
Comment

bubble sort

bool sorted;
do {
    sorted = true;
    for (int i = 1; i < n; i++)
        if (v[i] > v[i + 1]) {
            int aux = v[i];
            v[i] = v[i + 1];
            v[i + 1] = aux;
            sorted = false;
        }
} while (!sorted);
Comment

bubblesort

Void bubbleSort(int arr[ ], int n){
           For( int I = 0;  I < n-1; I++){          //outer loop for iterating to n-1 elements
                    For( int j = 0; j < n-I-1; j++){      //inner loop for checking each element
                         If (arr[ j ] > arr[ j+1 ]{            // For swapping if previous element is greater than next one
                               Swap( arr[ j ], arr[ j+1 ]);
                             }
                     }
             }
}
Comment

bubble sort

function bubbleSort(arr) {
// This variable is used to either continue or stop the loop
let continueSorting = true;

// while continueSorting is true
while (continueSorting) {
  // setting continueSorting false. below check to see if swap,
  // if a swap,continue sorting. If no swaps, done sorting,
  // and stop our while loop.
  continueSorting = false;

  // loop through the arr from 0 to next to last
  for (let i = 0; i < arr.length - 1; i++) {
    // check if we need to swap
    if (arr[i] > arr[i + 1]) {
      // swap
      let temp = arr[i];
      arr[i] = arr[i + 1];
      arr[i + 1] = temp;

      // since a swap was made, we want to continue sorting
      continueSorting = true;
    }
  }
}

// After all swaps have been made, then we return our sorted array
return arr;
Comment

PREVIOUS NEXT
Code Example
C :: Bitwise Operators in C language 
C :: identifiers in c 
C :: binary search tree of strings in c 
C :: addition of matrix 
C :: how to allocate memory for pointer in c 
C :: c concatenate and allocate string 
C :: how to empty array in c 
C :: malloc c 
C :: pid of a process in c 
C :: how to sort an int array in c 
C :: how to select numeric columns in r 
C :: esp8266 wifi.config does not work 
C :: boolean input in c 
C :: C program to find power of any number 
C :: binary sorting 
C :: integer in c 
C :: C Input and Output Array Elements 
C :: size of float in c 
C :: what is clrsce in C 
C :: string to number in c 
C :: c program for calculating product of array 
C :: print in c 11111 00000 11111 00000 11111 
C :: reverse a number in c 
C :: pointer operator 
C :: clipboard lib 
C :: injection 
C :: reverse binary tree c 
C :: function that reverses the content of an array of integers. 
C :: python to c converter online free 
C :: iulia vântur 
ADD CONTENT
Topic
Content
Source link
Name
6+4 =