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 sort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
public static void main(String[] args) {
int[] xr = {1, 3, 5, 2, 4};
sort(xr);
System.out.println(Arrays.toString(xr));
}
package com.SortingAlgorithm;
import java.util.Arrays;
public class Bubblesort {
public Bubblesort() {
}
public static void main(String[] args) {
int[] x = new int[]{5, 1, 4, 12, 7};
int n = x.length;
System.out.println("Original Array list is: " + Arrays.toString(x));
for(int i = 0; i < n - 1; ++i) {
// swapping of element occurs here
if (x[i] > x[i + 1]) {
int temp = x[i];
x[i] = x[i + 1];
x[i + 1] = temp;
}
}
System.out.println("The Sorted list is: " + Arrays.toString(x));
}
}
class Sort
{
static void bubbleSort(int arr[], int n)
{
if (n == 1) //passes are done
{
return;
}
for (int i=0; i<n-1; i++) //iteration through unsorted elements
{
if (arr[i] > arr[i+1]) //check if the elements are in order
{ //if not, swap them
int temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
}
bubbleSort(arr, n-1); //one pass done, proceed to the next
}
void display(int arr[]) //display the array
{
for (int i=0; i<arr.length; ++i)
{
System.out.print(arr[i]+" ");
}
}
public static void main(String[] args)
{
Sort ob = new Sort();
int arr[] = {6, 4, 5, 12, 2, 11, 9};
bubbleSort(arr, arr.length);
ob.display(arr);
}
}
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]))
public void bubbleSort(java.util.ArrayList aList) {
int n = aList.size();
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (aList.get(j - 1) > aList.get(j)) {
//swap elements
temp = aList.get(j - 1);
aList.set(j-1, aList.get(j));
aList.set(j, temp);
}
list.set(list.get(j+1), temp);