bubble sorting algorithm code example
Example 1: bubble sort in java
public static void bubbleSort(int arr[])
{
for (int i = 0; i < arr.length; i++)
{
for (int j = 0; j < (arr.length - 1 - i); j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
Example 2: bubble sort c
#include <bits/stdc++.h>
using namespace std;
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
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 3: 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
}
Example 4: Bubble Sort
import static java.lang.Integer.parseInt;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.StringTokenizer;
public class Day20_Sorting {
static int MB = 1 << 20;
static BufferedReader BR = new BufferedReader( new InputStreamReader(System.in, StandardCharsets.US_ASCII), 20 * MB);
static StringTokenizer st;
static String lastLine;
static void newLine() throws IOException {
lastLine = BR.readLine();
st = new StringTokenizer(lastLine);
}
public static void main(String[] args) throws IOException {
newLine();
int N = parseInt(st.nextToken());
newLine();
int[] A = new int[N];
for (int i = 0; i < N; i++) {
A[i] = parseInt(st.nextToken());
}
int numberOfSwapps = bubbleSort(N, A);
int firstElement = A[0];
int lastElement = A[N-1];
print(numberOfSwapps, firstElement, lastElement);
}
private static void print(int numberOfSwapps, int firstElement, int lastElement) {
StringBuilder sb = new StringBuilder();
sb.append("Array is sorted in ").append(numberOfSwapps).append(" swaps.\n");
sb.append("First Element: ").append(firstElement).append('\n');
sb.append("Last Element: ").append(lastElement).append('\n');
System.out.print(sb);
}
private static int bubbleSort(int N, int[] A) {
int cnt = 0;
for (int i = 0; i < N; i++) {
int numberOfSwaps = 0;
for (int j = 0; j < N - 1; j++) {
if (A[j] > A[j + 1]) {
swap(A, j , j + 1);
numberOfSwaps++;
}
}
cnt += numberOfSwaps;
if (numberOfSwaps == 0) {
break;
}
}
return cnt;
}
private static void swap(int[] a, int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}