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
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
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));
}
}
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us