bubble sort in java code example
Example 1: bubble sort java
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]){
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
}
Example 2: 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 3: bubble sort java
public class DemoBubbleSort
{
void bubbleSort(int[] arrNum)
{
int num = arrNum.length;
for(int a = 0; a < num - 1; a++)
{
for(int b = 0; b < num - a - 1; b++)
{
if(arrNum[b] > arrNum[b + 1])
{
int temp = arrNum[b];
arrNum[b] = arrNum[b + 1];
arrNum[b + 1] = temp;
}
}
}
}
void printingArray(int[] arrNum)
{
int number = arrNum.length;
for(int a = 0; a < number; ++a)
{
System.out.print(arrNum[a] + " ");
System.out.println();
}
}
public static void main(String[] args)
{
DemoBubbleSort bs = new DemoBubbleSort();
int[] arrSort = {65, 35, 25, 15, 23, 14, 95};
bs.bubbleSort(arrSort);
System.out.println("After sorting array: ");
bs.printingArray(arrSort);
}
}
Example 4: 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 5: java bubble sort short circuit
public static void BubbleSortShortSC(int[] array)
{
for(int i = 0; i < array.length - 1; i++)
{
boolean sorted = true;
for (int j = 0; j < array.length - i - 1; j++)
{
if(array[j] < array[j+1])
{
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
sorted = false;
}
}
if (sorted)
break;
}
}
Example 6: bubble sort integers
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;
}